!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(gg,mg){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(gg);function n(t){const n=[];let r=0;for(let s=0;s>6|192:(55296==(64512&e)&&s+1>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}const r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const s=[];for(let h=0;h>6,t=63&c;u||(t=64,a||(e=64)),s.push(r[i>>2],r[(3&i)<<4|o>>4],r[e],r[t])}return s.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n>10)),t[r++]=String.fromCharCode(56320+(1023&i))):(s=e[n++],i=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&s)<<6|63&i))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let u=0;u>4),64!==a&&(r.push(i<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},a=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};const s=()=>function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,i=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)}},o=()=>{try{return s()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||i()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}};function u(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function c(){return!function(){var e=null===(e=o())||void 0===e?void 0:e.forceEnvironment;if("node"===e)return 1;if("browser"!==e)try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return}}()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class h extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,h.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,d.prototype.create)}}class d{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],i=i?(r=n,i.replace(f,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",i=`${this.serviceName}: ${i} (${s}).`;return new h(s,i,n)}}const f=/\{\$([^}]+)}/g;function m(e){return e&&e._delegate?e._delegate:e}class g{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}(gd=l=l||{})[gd.DEBUG=0]="DEBUG",gd[gd.VERBOSE=1]="VERBOSE",gd[gd.INFO=2]="INFO",gd[gd.WARN=3]="WARN",gd[gd.ERROR=4]="ERROR",gd[gd.SILENT=5]="SILENT";const p={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},y=l.INFO,v={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},w=(e,t,...n)=>{if(!(t>>0),A=0;function C(e,t,n){return e.call.apply(e.bind,arguments)}function N(t,n,e){if(!t)throw Error();if(2parseFloat(ee)){Q=String(te);break e}}Q=ee}var ne={};function re(){return e=function(){let e=0;var t=U(String(Q)).split("."),n=U("9").split("."),r=Math.max(t.length,n.length);for(let a=0;0==e&&a>>0);function De(t){return"function"==typeof t?t:(t[xe]||(t[xe]=function(e){return t.handleEvent(e)}),t[xe])}function Ae(){M.call(this),this.i=new me(this),(this.P=this).I=null}function Ce(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t?t=new P(t,e):t instanceof P?t.target=t.target||e:(a=t,ge(t=new P(r,e),a)),a=!0,n)for(var s=n.length-1;0<=s;s--)var i=t.g=n[s],a=Ne(i,r,!0,t)&&a;if(a=Ne(i=t.g=e,r,!0,t)&&a,a=Ne(i,r,!1,t)&&a,n)for(s=0;snew Me,e=>e.reset());class Me{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function Fe(e,t){var n;Re||(n=T.Promise.resolve(void 0),Re=function(){n.then(Pe)}),Oe||(Re(),Oe=!0),Ve.add(e,t)}var Oe=!1,Ve=new class{constructor(){this.h=this.g=null}add(e,t){const n=Le.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Pe(){for(var e;e=function(){var e=Ve;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){T.setTimeout(()=>{throw e},0)}(e)}var t=Le;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Oe=!1}function qe(e,t){Ae.call(this),this.h=e||1,this.g=t||T,this.j=k(this.lb,this),this.l=Date.now()}function Be(e){e.ca=!1,e.R&&(e.g.clearTimeout(e.R),e.R=null)}function Ue(e,t,n){if("function"==typeof e)n&&(e=k(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=k(e.handleEvent,e)}return 2147483647{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}M(){super.M(),this.g&&(T.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Ke(e){M.call(this),this.h=e,this.g={}}L(Ke,M);var je=[];function $e(e,t,n,r){Array.isArray(n)||(n&&(je[0]=n.toString()),n=je);for(var s=0;sa.length?yt:(a=a.substr(u,o),i.C=u+o,a))),s==yt){4==t&&(e.o=4,tt(14),r=!1),We(e.j,e.m,null,"[Incomplete Response]");break}if(s==pt){e.o=4,tt(15),We(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}We(e.j,e.m,s,null),Dt(e,s)}var i,a,o,u;It(e)&&s!=yt&&s!=pt&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,tt(16),r=!1),e.i=e.i&&r,r?0>4&15).toString(16)+(15&e).toString(16)}Nt.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Pt(t,Bt,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Pt(t,Bt,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(Pt(n,"/"==n.charAt(0)?Gt:Ut,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Pt(n,jt)),e.join("")};var Bt=/[#\/\?@]/g,Ut=/[#\?:]/g,Gt=/[#\?]/g,Kt=/[#\?@]/g,jt=/#/g;function $t(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function Qt(n){n.g||(n.g=new Map,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n=e.j}function tn(e){return e.h?1:e.g?e.g.size:0}function nn(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function rn(e,t){e.g?e.g.add(t):e.h=t}function sn(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function an(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return O(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function on(){}function un(){this.g=new on}function cn(e,t,n,r,s){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,s(r)}catch(e){}}function hn(e){this.l=e.ac||null,this.j=e.jb||!1}function ln(e,t){Ae.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=dn,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}Jt.prototype.cancel=function(){if(this.i=an(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}},on.prototype.stringify=function(e){return T.JSON.stringify(e,void 0)},on.prototype.parse=function(e){return T.JSON.parse(e,void 0)},L(hn,at),hn.prototype.g=function(){return new ln(this.l,this.j)},hn.prototype.i=(Zt={},function(){return Zt}),L(ln,Ae);var dn=0;function fn(e){e.j.read().then(e.Ta.bind(e)).catch(e.ga.bind(e))}function gn(e){e.readyState=4,e.l=null,e.j=null,e.A=null,mn(e)}function mn(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(I=ln.prototype).open=function(e,t){if(this.readyState!=dn)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,mn(this)},I.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||T).fetch(new Request(this.B,t)).then(this.Wa.bind(this),this.ga.bind(this))},I.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,gn(this)),this.readyState=dn},I.Wa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,mn(this)),this.g&&(this.readyState=3,mn(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ua.bind(this),this.ga.bind(this));else if(void 0!==T.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;fn(this)}else e.text().then(this.Va.bind(this),this.ga.bind(this))},I.Ta=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?gn:mn)(this),3==this.readyState&&fn(this))},I.Va=function(e){this.g&&(this.response=this.responseText=e,gn(this))},I.Ua=function(e){this.g&&(this.response=e,gn(this))},I.ga=function(){this.g&&gn(this)},I.setRequestHeader=function(e,t){this.v.append(e,t)},I.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},I.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(ln.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var pn=T.JSON.parse;function yn(e){Ae.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=vn,this.K=this.L=!1}L(yn,Ae);var vn="",wn=/^https?$/i,In=["POST","PUT"];function bn(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,En(e),_n(e)}function En(e){e.D||(e.D=!0,Ce(e,"complete"),Ce(e,"error"))}function Tn(e){if(e.h&&void 0!==E&&(!e.C[1]||4!=xn(e)||2!=e.aa()))if(e.v&&4==xn(e))Ue(e.Ha,0,e);else if(Ce(e,"readystatechange"),4==xn(e)){e.h=!1;try{var t,n,r,s,i=e.aa();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var a=!0;break e;default:a=!1}if((t=a)||((n=0===i)&&(!(s=String(e.H).match(Ct)[1]||null)&&T.self&&T.self.location&&(s=(r=T.self.location.protocol).substr(0,r.length-1)),n=!wn.test(s?s.toLowerCase():"")),t=n),t)Ce(e,"complete"),Ce(e,"success");else{e.m=6;try{var o=2=r.h.j-(r.m?1:0)||(r.m?(r.i=s.D.concat(r.i),0):1==r.G||2==r.G||r.C>=(r.Za?0:r.$a)||(r.m=rt(k(r.Ja,r,s),$n(r,r.C)),r.C++,0))))&&(2!=a||!Bn(e)))switch(i&&0"content-type"==e.toLowerCase()),s=T.FormData&&e instanceof T.FormData,0<=F(In,t)&&!r&&!s&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[i,a]of n)this.g.setRequestHeader(i,a);this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{Sn(this),0`${this.name}: [code=${this.code}]: ${this.message}`}}class Sr{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class xr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Dr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(fr.UNAUTHENTICATED))}shutdown(){}}class Ar{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class Cr{constructor(e){this.t=e,this.currentUser=fr.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const s=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let i=new Sr;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Sr,t.enqueueRetryable(()=>s(this.currentUser))};const a=()=>{const e=i;t.enqueueRetryable(async()=>{await e.promise,await s(this.currentUser)})},o=e=>{yr("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),a()};this.t.onInit(e=>o(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?o(e):(yr("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Sr))},0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(yr("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(Er("string"==typeof e.accessToken),new xr(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return Er(null===e||"string"==typeof e),new fr(e)}}class Nr{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r,this.type="FirstParty",this.user=fr.FIRST_PARTY,this.p=new Map}I(){return this.g?this.g():(Er(!("object"!=typeof this.h||null===this.h||!this.h.auth||!this.h.auth.getAuthHeaderValueForFirstParty)),this.h.auth.getAuthHeaderValueForFirstParty([]))}get headers(){this.p.set("X-Goog-AuthUser",this.l);var e=this.I();return e&&this.p.set("Authorization",e),this.m&&this.p.set("X-Goog-Iam-Authorization-Token",this.m),this.p}}class kr{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r}getToken(){return Promise.resolve(new Nr(this.h,this.l,this.m,this.g))}start(e,t){e.enqueueRetryable(()=>t(fr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Rr{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0{null!=e.error&&yr("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.A;return this.A=e.token,yr("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const s=e=>{yr("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.T.onInit(e=>s(e)),setTimeout(()=>{var e;this.appCheck||((e=this.T.getImmediate({optional:!0}))?s(e):yr("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Er("string"==typeof e.token),this.A=e.token,new Rr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Mr{static R(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var s=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;er(e,n[t]))}function Vr(e){return e+"\0"}class Pr{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new _r(Tr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new _r(Tr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new _r(Tr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new _r(Tr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return Pr.fromMillis(Date.now())}static fromDate(e){return Pr.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new Pr(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Fr(this.nanoseconds,e.nanoseconds):Fr(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class qr{constructor(e){this.timestamp=e}static fromTimestamp(e){return new qr(e)}static min(){return new qr(new Pr(0,0))}static max(){return new qr(new Pr(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class Br{constructor(e,t,n){void 0===t?t=0:t>e.length&&br(),void 0===n?n=e.length-t:n>e.length-t&&br(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===Br.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof Br?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.lengths)return 1}return e.lengtht.length?1:0}}class Ur extends Br{construct(e,t,n){return new Ur(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new _r(Tr.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!Kr.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Kr(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var s=()=>{if(0===n.length)throw new _r(Tr.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let i=!1;for(;r2===e.kind)}function zr(e){return e.fields.filter(e=>2!==e.kind)}$r.UNKNOWN_ID=-1;class Wr{constructor(e,t){this.fieldPath=e,this.kind=t}}class Hr{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new Hr(0,Jr.min())}}function Yr(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=qr.fromTimestamp(1e9===r?new Pr(n+1,0):new Pr(n,r));return new Jr(r,jr.empty(),t)}function Xr(e){return new Jr(e.readTime,e.key,-1)}class Jr{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Jr(qr.min(),jr.empty(),-1)}static max(){return new Jr(qr.max(),jr.empty(),-1)}}function Zr(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=jr.comparator(e.documentKey,t.documentKey),0!==n?n:Fr(e.largestBatchId,t.largestBatchId))}const es="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class ts{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function ns(e){if(e.code!==Tr.FAILED_PRECONDITION||e.message!==es)throw e;yr("LocalStore","Unexpectedly lost primary lease")}class rs{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,s){return this.callbackAttached&&br(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(s,this.error):this.wrapSuccess(r,this.result):new rs((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(s,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof rs?t:rs.resolve(t)}catch(e){return rs.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):rs.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):rs.reject(t)}static resolve(n){return new rs((e,t)=>{e(n)})}static reject(n){return new rs((e,t)=>{t(n)})}static waitFor(e){return new rs((t,n)=>{let r=0,s=0,i=!1;e.forEach(e=>{++r,e.next(()=>{++s,i&&s===r&&t()},e=>n(e))}),i=!0,s===r&&t()})}static or(e){let t=rs.resolve(!1);for(const n of e)t=t.next(e=>e?rs.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}static mapArray(o,u){return new rs((t,n)=>{const r=o.length,s=new Array(r);let i=0;for(let e=0;e{s[a]=e,++i,i===r&&t(s)},e=>n(e))}})}static doWhile(r,s){return new rs((e,t)=>{const n=()=>{!0===r()?s().next(()=>{n()},t):e()};n()})}}class ss{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.P=new Sr,this.transaction.oncomplete=()=>{this.P.resolve()},this.transaction.onabort=()=>{e.error?this.P.reject(new os(n,e.error)):this.P.resolve()},this.transaction.onerror=e=>{var t=ds(e.target.error);this.P.reject(new os(n,t))}}static open(e,t,n,r){try{return new ss(t,e.transaction(r,n))}catch(e){throw new os(t,e)}}get v(){return this.P.promise}abort(e){e&&this.P.reject(e),this.aborted||(yr("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}V(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new cs(t)}}class is{constructor(e,t,n){this.name=e,this.version=t,this.S=n,12.2===is.D(u())&&vr("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return yr("SimpleDb","Removing database:",e),hs(window.indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!function(){try{return"object"==typeof indexedDB}catch(e){return}}())return!1;if(is.N())return!0;const e=u(),t=is.D(e),n=0{const s=indexedDB.open(this.name,this.version);s.onsuccess=e=>{var t=e.target.result;n(t)},s.onblocked=()=>{r(new os(i,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},s.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new _r(Tr.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new _r(Tr.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new os(i,t))},s.onupgradeneeded=e=>{yr("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.S.$(t,s.transaction,e.oldVersion,this.version).next(()=>{yr("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.B&&(this.db.onversionchange=e=>this.B(e)),this.db}L(t){this.B=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var s="readonly"===t;let i=0;for(;;){++i;try{this.db=await this.F(e);const t=ss.open(this.db,e,s?"readonly":"readwrite",n),i=r(t).next(e=>(t.V(),e)).catch(e=>(t.abort(e),rs.reject(e))).toPromise();return i.catch(()=>{}),await t.v,i}catch(e){const t=e,n="FirebaseError"!==t.name&&i<3;if(yr("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class as{constructor(e){this.q=e,this.U=!1,this.K=null}get isDone(){return this.U}get G(){return this.K}set cursor(e){this.q=e}done(){this.U=!0}j(e){this.K=e}delete(){return hs(this.q.delete())}}class os extends _r{constructor(e,t){super(Tr.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function us(e){return"IndexedDbTransactionError"===e.name}class cs{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(yr("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(yr("SimpleDb","PUT",this.store.name,"",e),this.store.put(e)),hs(n)}add(e){return yr("SimpleDb","ADD",this.store.name,e,e),hs(this.store.add(e))}get(t){return hs(this.store.get(t)).next(e=>(yr("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return yr("SimpleDb","DELETE",this.store.name,e),hs(this.store.delete(e))}count(){return yr("SimpleDb","COUNT",this.store.name),hs(this.store.count())}W(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.H(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new rs((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}J(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new rs((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}Y(e,t){yr("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.X=!1;var r=this.cursor(n);return this.H(r,(e,t,n)=>n.delete())}Z(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.H(r,t)}tt(s){const e=this.cursor({});return new rs((n,r)=>{e.onerror=e=>{var t=ds(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?s(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}H(e,i){const a=[];return new rs((s,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new as(t),r=i(t.primaryKey,t.value,n);if(r instanceof rs){const e=r.catch(e=>(n.done(),rs.reject(e)));a.push(e)}n.isDone?s():null===n.G?t.continue():t.continue(n.G)}else s()}}).next(()=>rs.waitFor(a))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.X?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function hs(e){return new rs((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=ds(e.target.error);r(t)}})}let ls=!1;function ds(e){const t=is.D(u());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new _r("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return ls||(ls=!0,setTimeout(()=>{throw e},0)),e}}return e}class fs{constructor(e,t){this.asyncQueue=e,this.et=t,this.task=null}start(){this.nt(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}nt(e){yr("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{yr("IndexBackiller",`Documents written: ${await this.et.st()}`)}catch(e){us(e)?yr("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await ns(e)}await this.nt(6e4)})}}class gs{constructor(e,t){this.localStore=e,this.persistence=t}async st(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.it(e,t))}it(e,t){const n=new Set;let r=t,s=!0;return rs.doWhile(()=>!0===s&&0this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(s=!1):(yr("IndexBackiller",`Processing collection: ${t}`),this.rt(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}rt(r,s,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,s).next(n=>this.localStore.localDocuments.getNextDocuments(r,s,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.ot(n,e)).next(e=>(yr("IndexBackiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,s,e))).next(()=>t.size)}))}ot(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=Xr(t);0this.ut(e),this.ct=e=>t.writeSequenceNumber(e))}ut(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.ct&&this.ct(e),e}}ms.at=-1;class ps{constructor(e,t,n,r,s,i,a,o){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=a,this.useFetchStreams=o}}class ys{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new ys("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof ys&&e.projectId===this.projectId&&e.database===this.database}}function vs(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ws(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function Is(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function bs(e){return null==e}function Es(e){return 0===e&&1/e==-1/0}function Ts(e){return"number"==typeof e&&Number.isInteger(e)&&!Es(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class _s{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new _s(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;neMs(e,t))}function Os(e,t){if(e===t)return 0;var n,r,s,i,a=Ls(e),o=Ls(t);if(a!==o)return Fr(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Fr(e.booleanValue,t.booleanValue);case 2:return r=t,s=Ds(e.integerValue||e.doubleValue),i=Ds(r.integerValue||r.doubleValue),sn.mapValue.fields[e]=$s(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=$s(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Qs(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function zs(e,t){var n=Os(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Ws(e,t){var n=Os(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Hs{constructor(e,t){this.position=e,this.inclusive=t}}function Ys(e,t,n){let r=0;for(let s=0;s":return 0=":return 0<=e;default:return br()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class ei extends Js{constructor(e,t){super(),this.filters=e,this.op=t,this.ht=null}static create(e,t){return new ei(e,t)}matches(t){return ti(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ht||(this.ht=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ht}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){var e=this.lt(e=>e.isInequality());return null!==e?e.field:null}lt(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function ti(e){return"and"===e.op}function ni(e){return"or"===e.op}function ri(e){return si(e)&&ti(e)}function si(e){for(const t of e.filters)if(t instanceof ei)return!1;return!0}function ii(e,t){var n=e.filters.concat(t);return ei.create(n,e.op)}function ai(e){return e instanceof Zs?`${(t=e).field.canonicalString()} ${t.op} ${Ps(t.value)}`:e instanceof ei?(e=e).op.toString()+" {"+e.getFilters().map(ai).join(" ,")+"}":"Filter";var t}class oi extends Zs{constructor(e,t,n){super(e,t,n),this.key=jr.fromName(n.referenceValue)}matches(e){var t=jr.comparator(e.key,this.key);return this.matchesComparison(t)}}class ui extends Zs{constructor(e,t){super(e,"in",t),this.keys=hi(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class ci extends Zs{constructor(e,t){super(e,"not-in",t),this.keys=hi(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function hi(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>jr.fromName(e.referenceValue))}class li extends Zs{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return Us(t)&&Fs(t.arrayValue,this.value)}}class di extends Zs{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Fs(this.value.arrayValue,t)}}class fi extends Zs{constructor(e,t){super(e,"not-in",t)}matches(e){if(Fs(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Fs(this.value.arrayValue,t)}}class gi extends Zs{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Us(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Fs(this.value.arrayValue,e))}}class mi{constructor(e,t="asc"){this.field=e,this.dir=t}}class pi{constructor(e,t){this.comparator=e,this.root=t||vi.EMPTY}insert(e,t){return new pi(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,vi.BLACK,null,null))}remove(e){return new pi(this.comparator,this.root.remove(e,this.comparator).copy(null,null,vi.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new yi(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new yi(this.root,e,this.comparator,!1)}getReverseIterator(){return new yi(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new yi(this.root,e,this.comparator,!0)}}class yi{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,t&&r&&(s*=-1),s<0)e=this.isReverse?e.left:e.right;else{if(0===s){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new Ii(this.data.getIterator())}getIteratorFrom(e){return new Ii(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size{t=t.add(e)}),t}isEqual(e){if(!(e instanceof wi))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new wi(this.comparator);return t.data=e,t}}class Ii{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function bi(e){return e.hasNext()?e.getNext():void 0}class Ei{constructor(e){(this.fields=e).sort(Kr.comparator)}static empty(){return new Ei([])}unionWith(e){let t=new wi(Kr.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new Ei(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Or(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class Ti{constructor(e){this.value=e}static empty(){return new Ti({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,s),r={},s=[],n=t.popLast()}e?r[t.lastSegment()]=$s(e):s.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,s)}delete(e){const t=this.field(e.popLast());js(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ms(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;rn[e]=t);for(const e of t)delete n[e]}clone(){return new Ti($s(this.value))}}class _i{constructor(e,t,n,r,s,i,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=s,this.data=i,this.documentState=a}static newInvalidDocument(e){return new _i(e,0,qr.min(),qr.min(),qr.min(),Ti.empty(),0)}static newFoundDocument(e,t,n,r){return new _i(e,1,t,qr.min(),n,r,0)}static newNoDocument(e,t){return new _i(e,2,t,qr.min(),qr.min(),Ti.empty(),0)}static newUnknownDocument(e,t){return new _i(e,3,t,qr.min(),qr.min(),Ti.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(qr.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Ti.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Ti.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=qr.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof _i&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new _i(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Si{constructor(e,t=null,n=[],r=[],s=null,i=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=a,this.ft=null}}function xi(e,t=null,n=[],r=[],s=null,i=null,a=null){return new Si(e,t,n,r,s,i,a)}function Di(e){const t=e;if(null===t.ft){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function t(e){if(e instanceof Zs)return e.field.canonicalString()+e.op.toString()+Ps(e.value);if(ri(e))return e.filters.map(e=>t(e)).join(",");var n=e.filters.map(e=>t(e)).join(",");return`${e.op}(${n})`}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),bs(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>Ps(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>Ps(e)).join(",")),t.ft=e}return t.ft}function Ai(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let s=0;se&&r(t,s.filters[n]),!0):void br();var s,n,i}(e.filters[i],t.filters[i]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Xs(e.startAt,t.startAt)&&Xs(e.endAt,t.endAt)}function Ci(e){return jr.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Ni(e,t){return e.filters.filter(e=>e instanceof Zs&&e.field.isEqual(t))}function ki(t,n,r){let s=Rs,i=!0;for(const r of Ni(t,n)){let e=Rs,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?Rs:"booleanValue"in a?{booleanValue:!1}:"integerValue"in a||"doubleValue"in a?{doubleValue:NaN}:"timestampValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in a?{stringValue:""}:"bytesValue"in a?{bytesValue:""}:"referenceValue"in a?qs(ys.empty(),jr.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:br();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Rs}zs({value:s,inclusive:i},{value:e,inclusive:t})<0&&(s=e,i=t)}var a;if(null!==r)for(let e=0;e=":case">":e="nullValue"in(a=r.value)?{booleanValue:!1}:"booleanValue"in a?{doubleValue:NaN}:"integerValue"in a||"doubleValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in a?{stringValue:""}:"stringValue"in a?{bytesValue:""}:"bytesValue"in a?qs(ys.empty(),jr.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?ks:br(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=ks}0function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>Ps(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>Ps(e)).join(",")),`Target(${t})`}(Ui(e))}; limitType=${e.limitType})`}function zi(n,e){return e.isFoundDocument()&&(s=n,a=(i=e).key.path,null!==s.collectionGroup?i.key.hasCollectionId(s.collectionGroup)&&s.path.isPrefixOf(a):jr.isDocumentKey(s.path)?s.path.isEqual(a):s.path.isImmediateParentOf(a))&&function(e){for(const t of Bi(n))if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(s=e,(!(e=n).startAt||(t=e.startAt,r=Ys(t,Bi(e),s),t.inclusive?r<=0:r<0))&&(!e.endAt||(t=e.endAt,r=Ys(t,Bi(e),s),t.inclusive?0<=r:0{let n=!1;for(const r of Bi(s)){const s=function(e,s,t){var n=e.field.isKeyField()?jr.comparator(s.key,t.key):function(e,t){var n=s.data.field(e),r=t.data.field(e);return null!==n&&null!==r?Os(n,r):br()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return br()}}(r,e,t);if(0!==s)return s;n=n||r.field.isKeyField()}return 0}}function Yi(e,t){if(e.wt){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Es(t)?"-0":t}}function Xi(e){return{integerValue:""+e}}function Ji(e,t){return Ts(t)?Xi(t):Yi(e,t)}class Zi{constructor(){this._=void 0}}function ea(e,t){return e instanceof aa?Bs(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class ta extends Zi{}class na extends Zi{constructor(e){super(),this.elements=e}}function ra(e,t){const n=ua(t);for(const t of e.elements)n.some(e=>Ms(e,t))||n.push(t);return{arrayValue:{values:n}}}class sa extends Zi{constructor(e){super(),this.elements=e}}function ia(e,t){let n=ua(t);for(const t of e.elements)n=n.filter(e=>!Ms(e,t));return{arrayValue:{values:n}}}class aa extends Zi{constructor(e,t){super(),this.yt=e,this.gt=t}}function oa(e){return Ds(e.integerValue||e.doubleValue)}function ua(e){return Us(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class ca{constructor(e,t){this.field=e,this.transform=t}}class ha{constructor(e,t){this.version=e,this.transformResults=t}}class la{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new la}static exists(e){return new la(void 0,e)}static updateTime(e){return new la(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function da(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class fa{}function ga(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new Ta(e.key,la.none()):new va(e.key,e.data,la.none());{const s=e.data,i=Ti.empty();let t=new wi(Kr.comparator);for(var r of n.fields)if(!t.has(r)){let e=s.field(r);null===e&&1e.field))}(e,t,n,r):(t=t,n=n,da(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function ya(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&Or(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof na&&t instanceof na||e instanceof sa&&t instanceof sa?Or(e.elements,t.elements,Ms):e instanceof aa&&t instanceof aa?Ms(e.gt,t.gt):e instanceof ta&&t instanceof ta)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}class va extends fa{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class wa extends fa{constructor(e,t,n,r,s=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=s,this.type=1}getFieldMask(){return this.fieldMask}}function Ia(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function ba(e,t,n){const r=new Map;Er(e.length===n.length);for(let h=0;h{for(const[e,n]of t)r(e,n)})}isEmpty(){return Is(this.inner)}size(){return this.innerSize}}const Ca=new pi(jr.comparator);const Na=new pi(jr.comparator);function ka(...e){let t=Na;for(const n of e)t=t.insert(n.key,n);return t}function Ra(e){let n=Na;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function La(){return new Aa(e=>e.toString(),(e,t)=>e.isEqual(t))}const Ma=new pi(jr.comparator),Fa=new wi(jr.comparator);function Oa(...e){let t=Fa;for(const n of e)t=t.add(n);return t}const Va=new wi(Fr);class Pa{constructor(e,t,n,r,s){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=s}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,qa.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Pa(qr.min(),r,Va,Ca,Oa())}}class qa{constructor(e,t,n,r,s){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=s}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new qa(n,t,Oa(),Oa(),Oa())}}class Ba{constructor(e,t,n,r){this.It=e,this.removedTargetIds=t,this.key=n,this.Tt=r}}class Ua{constructor(e,t){this.targetId=e,this.Et=t}}class Ga{constructor(e,t,n=_s.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class Ka{constructor(){this.At=0,this.Rt=Qa(),this.bt=_s.EMPTY_BYTE_STRING,this.Pt=!1,this.vt=!0}get current(){return this.Pt}get resumeToken(){return this.bt}get Vt(){return 0!==this.At}get St(){return this.vt}Dt(e){0{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:s=s.add(e);break;default:br()}}),new qa(this.bt,this.Pt,n,r,s)}xt(){this.vt=!1,this.Rt=Qa()}Nt(e,t){this.vt=!0,this.Rt=this.Rt.insert(e,t)}kt(e){this.vt=!0,this.Rt=this.Rt.remove(e)}Ot(){this.At+=1}Mt(){--this.At}Ft(){this.vt=!0,this.Pt=!0}}class ja{constructor(e){this.$t=e,this.Bt=new Map,this.Lt=Ca,this.qt=$a(),this.Ut=new wi(Fr)}Kt(e){for(const t of e.It)e.Tt&&e.Tt.isFoundDocument()?this.Gt(t,e.Tt):this.Qt(t,e.key,e.Tt);for(const n of e.removedTargetIds)this.Qt(n,e.key,e.Tt)}jt(n){this.forEachTarget(n,e=>{const t=this.Wt(e);switch(n.state){case 0:this.zt(e)&&t.Dt(n.resumeToken);break;case 1:t.Mt(),t.Vt||t.xt(),t.Dt(n.resumeToken);break;case 2:t.Mt(),t.Vt||this.removeTarget(e);break;case 3:this.zt(e)&&(t.Ft(),t.Dt(n.resumeToken));break;case 4:this.zt(e)&&(this.Ht(e),t.Dt(n.resumeToken));break;default:br()}})}forEachTarget(e,n){0{this.zt(t)&&n(t)})}Jt(e){const t=e.targetId,n=e.Et.count,r=this.Yt(t);if(r){const e=r.target;if(Ci(e))if(0===n){const n=new jr(e.path);this.Qt(t,n,_i.newNoDocument(n,qr.min()))}else Er(1===n);else this.Xt(t)!==n&&(this.Ht(t),this.Ut=this.Ut.add(t))}}Zt(r){const s=new Map;this.Bt.forEach((e,t)=>{var n=this.Yt(t);if(n){if(e.current&&Ci(n.target)){const s=new jr(n.target.path);null!==this.Lt.get(s)||this.te(t,s)||this.Qt(t,s,_i.newNoDocument(s,r))}e.St&&(s.set(t,e.Ct()),e.xt())}});let i=Oa();this.qt.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.Yt(e);return!t||2===t.purpose||(n=!1)}),n&&(i=i.add(e))}),this.Lt.forEach((e,t)=>t.setReadTime(r));var e=new Pa(r,s,this.Ut,this.Lt,i);return this.Lt=Ca,this.qt=$a(),this.Ut=new wi(Fr),e}Gt(e,t){var n;this.zt(e)&&(n=this.te(e,t.key)?2:0,this.Wt(e).Nt(t.key,n),this.Lt=this.Lt.insert(t.key,t),this.qt=this.qt.insert(t.key,this.ee(t.key).add(e)))}Qt(e,t,n){if(this.zt(e)){const r=this.Wt(e);this.te(e,t)?r.Nt(t,1):r.kt(t),this.qt=this.qt.insert(t,this.ee(t).delete(e)),n&&(this.Lt=this.Lt.insert(t,n))}}removeTarget(e){this.Bt.delete(e)}Xt(e){var t=this.Wt(e).Ct();return this.$t.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ot(e){this.Wt(e).Ot()}Wt(e){let t=this.Bt.get(e);return t||(t=new Ka,this.Bt.set(e,t)),t}ee(e){let t=this.qt.get(e);return t||(t=new wi(Fr),this.qt=this.qt.insert(e,t)),t}zt(e){var t=null!==this.Yt(e);return t||yr("WatchChangeAggregator","Detected inactive target",e),t}Yt(e){var t=this.Bt.get(e);return t&&t.Vt?null:this.$t.ne(e)}Ht(t){this.Bt.set(t,new Ka),this.$t.getRemoteKeysForTarget(t).forEach(e=>{this.Qt(t,e,null)})}te(e,t){return this.$t.getRemoteKeysForTarget(e).has(t)}}function $a(){return new pi(jr.comparator)}function Qa(){return new pi(jr.comparator)}const za={asc:"ASCENDING",desc:"DESCENDING"},Wa={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},Ha={and:"AND",or:"OR"};class Ya{constructor(e,t){this.databaseId=e,this.wt=t}}function Xa(e,t){return e.wt?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function Ja(e,t){return e.wt?t.toBase64():t.toUint8Array()}function Za(e){return Er(!!e),qr.fromTimestamp((t=xs(e),new Pr(t.seconds,t.nanos)));var t}function eo(e,t){return e=e,new Ur(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function to(e){var t=Ur.fromString(e);return Er(Io(t)),t}function no(e,t){return eo(e.databaseId,t.path)}function ro(e,t){const n=to(t);if(n.get(1)!==e.databaseId.projectId)throw new _r(Tr.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new _r(Tr.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new jr(oo(n))}function so(e,t){return eo(e.databaseId,t)}function io(e){var t=to(e);return 4===t.length?Ur.emptyPath():oo(t)}function ao(e){return new Ur(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function oo(e){return Er(4t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof _a))return br();n={verify:no(e,t.key)}}return 0function(e){var t=e.transform;if(t instanceof ta)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof na)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof sa)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof aa)return{fieldPath:e.field.canonicalString(),increment:t.gt};throw br()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,Xa(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:br()),n;var r}function lo(t,n){const e=n.currentDocument?void 0!==(s=n.currentDocument).updateTime?la.updateTime(Za(s.updateTime)):void 0!==s.exists?la.exists(s.exists):la.none():la.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)Er("REQUEST_TIME"===t.setToServerValue),n=new ta;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new na(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new sa(e)}else"increment"in t?n=new aa(e,t.increment):br();var r=Kr.fromServerFormat(t.fieldPath);return new ca(r,n)}(t,e)):[];var s;if(n.update){n.update.name;var i=ro(t,n.update.name),a=new Ti({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new Ei(e.map(e=>Kr.fromServerFormat(e)))}();return new wa(i,a,t,e,r)}return new va(i,a,e,r)}if(n.delete){const r=ro(t,n.delete);return new Ta(r,e)}if(n.verify){const r=ro(t,n.verify);return new _a(r,e)}return br()}function fo(e,t){return{documents:[so(e,t.path)]}}function go(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=so(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=so(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var s=function(e){if(0!==e.length)return function n(e){return e instanceof Zs?function(e){if("=="===e.op){if(Ks(e.value))return{unaryFilter:{field:vo(e.field),op:"IS_NAN"}};if(Gs(e.value))return{unaryFilter:{field:vo(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Ks(e.value))return{unaryFilter:{field:vo(e.field),op:"IS_NOT_NAN"}};if(Gs(e.value))return{unaryFilter:{field:vo(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:vo(e.field),op:po(e.op),value:e.value}}}(e):e instanceof ei?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:yo(e.op),filters:t}}}(e):br()}(ei.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);s=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:vo(e.field),direction:(e=e.dir,za[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);var i,s=(i=t.limit,e.wt||bs(i)?i:{value:i});return null!==s&&(n.structuredQuery.limit=s),t.startAt&&(n.structuredQuery.startAt={before:(s=t.startAt).inclusive,values:s.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function mo(e){let t=io(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let s=null;if(0";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return br()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return ei.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return br()}}(e.compositeFilter.op))}(e):br()}(n.where);return e instanceof ei&&ri(e)?e.getFilters():[e]}());let a=[];n.orderBy&&(a=n.orderBy.map(e=>function(e){return new mi(wo(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let o=null;var u,c,h,l;n.limit&&(o=(e=n.limit,bs(u="object"==typeof e?e.value:e)?null:u));let d=null;n.startAt&&(d=(c=n.startAt,l=!!c.before,h=c.values||[],new Hs(h,l)));let f=null;return n.endAt&&(f=(c=n.endAt,h=!c.before,l=c.values||[],new Hs(l,h))),Mi(t,s,a,i,o,"F",d,f)}function po(e){return Wa[e]}function yo(e){return Ha[e]}function vo(e){return{fieldPath:e.canonicalString()}}function wo(e){return Kr.fromServerFormat(e.fieldPath)}function Io(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function bo(e){let t="";for(let n=0;nr)&&br(),t.charAt(n+1)){case"":const r=t.substring(a,n);let e;0===i.length?e=r:(i+=r,e=i,i=""),s.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:br()}a=n+2}return new Ur(s)}const _o=["userId","batchId"];function So(e,t){return[e,bo(t)]}function xo(e,t,n){return[e,bo(t),n]}const Do={},Ao=["prefixPath","collectionGroup","readTime","documentId"],Co=["prefixPath","collectionGroup","documentId"],No=["collectionGroup","readTime","prefixPath","documentId"],ko=["canonicalId","targetId"],Ro=["targetId","path"],Lo=["path","targetId"],Mo=["collectionId","parent"],Fo=["indexId","uid"],Oo=["uid","sequenceNumber"],Vo=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Po=["indexId","uid","orderedDocumentKey"],qo=["userId","collectionPath","documentId"],Bo=["userId","collectionPath","largestBatchId"],Uo=["userId","collectionGroup","largestBatchId"],Go=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],Ko=[...Go,"documentOverlays"],jo=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],$o=jo,Qo=[...$o,"indexConfiguration","indexState","indexEntries"];class zo extends ts{constructor(e,t){super(),this.se=e,this.currentSequenceNumber=t}}function Wo(e,t){var n=e;return is.M(n.se,t)}class Ho{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r{const t=i.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var s=ga(n,r);null!==s&&o.set(e.key,s),n.isValidDocument()||n.convertToNoDocument(qr.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Oa())}isEqual(e){return this.batchId===e.batchId&&Or(this.mutations,e.mutations,(e,t)=>ya(e,t))&&Or(this.baseMutations,e.baseMutations,(e,t)=>ya(e,t))}}class Yo{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Er(e.mutations.length===n.length);let r=Ma;var s=e.mutations;for(let i=0;ilo(t.ie,e));for(let i=0;ilo(t.ie,e)),s=Pr.fromMillis(e.localWriteTimeMs);return new Ho(e.batchId,s,n,r)}function iu(e){var t,n=ru(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?ru(e.lastLimboFreeSnapshotVersion):qr.min();let s;return s=void 0!==e.query.documents?(Er(1===(t=e.query).documents.length),Ui(Fi(io(t.documents[0])))):Ui(mo(e.query)),new Jo(s,e.targetId,0,e.lastListenSequenceNumber,n,r,_s.fromBase64String(e.resumeToken))}function au(e,t){var n=nu(t.snapshotVersion),r=nu(t.lastLimboFreeSnapshotVersion),s=(Ci(t.target)?fo:go)(e.ie,t.target),i=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Di(t.target),readTime:n,resumeToken:i,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:s}}function ou(e){var t=mo({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Ki(t,t.limit,"L"):t}function uu(e,t){return new Xo(t.largestBatchId,lo(e.ie,t.overlayMutation))}function cu(e,t){var n=t.path.lastSegment();return[e,bo(t.path.popLast()),n]}function hu(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:nu(r.readTime),documentKey:bo(r.documentKey.path),largestBatchId:r.largestBatchId}}class lu{getBundleMetadata(e,t){return du(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:ru(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return du(e).put({bundleId:(n=t).id,createTime:nu(Za(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return fu(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:ou(t.bundledQuery),readTime:ru(t.readTime)};var t})}saveNamedQuery(e,t){return fu(e).put({name:(t=t).name,readTime:nu(Za(t.readTime)),bundledQuery:t.bundledQuery})}}function du(e){return Wo(e,"bundles")}function fu(e){return Wo(e,"namedQueries")}class gu{constructor(e,t){this.yt=e,this.userId=t}static re(e,t){var n=t.uid||"";return new gu(e,n)}getOverlay(e,t){return mu(e).get(cu(this.userId,t)).next(e=>e?uu(this.yt,e):null)}getOverlays(e,t){const n=La();return rs.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,s,e){const i=[];return e.forEach((e,t)=>{var n=new Xo(s,t);i.push(this.oe(r,n))}),rs.waitFor(i)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(bo(e.getCollectionPath())));const s=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);s.push(mu(n).Y("collectionPathOverlayIndex",t))}),rs.waitFor(s)}getOverlaysForCollection(e,t,n){const r=La(),s=bo(t),i=IDBKeyRange.bound([this.userId,s,n],[this.userId,s,Number.POSITIVE_INFINITY],!0);return mu(e).W("collectionPathOverlayIndex",i).next(e=>{for(const t of e){const e=uu(this.yt,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,s){const i=La();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return mu(e).Z({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=uu(this.yt,t);i.size()i)}oe(e,t){return mu(e).put(function(e,t,n){var[,r,s]=cu(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:ho(e.ie,n.mutation)}}(this.yt,this.userId,t))}}function mu(e){return Wo(e,"documentOverlays")}class pu{constructor(){}ue(e,t){this.ce(e,t),t.ae()}ce(e,t){var n,r;"nullValue"in e?this.he(t,5):"booleanValue"in e?(this.he(t,10),t.le(e.booleanValue?1:0)):"integerValue"in e?(this.he(t,15),t.le(Ds(e.integerValue))):"doubleValue"in e?(n=Ds(e.doubleValue),isNaN(n)?this.he(t,13):(this.he(t,15),Es(n)?t.le(0):t.le(n))):"timestampValue"in e?(r=e.timestampValue,this.he(t,20),"string"==typeof r?t.fe(r):(t.fe(`${r.seconds||""}`),t.le(r.nanos||0))):"stringValue"in e?(this.de(e.stringValue,t),this._e(t)):"bytesValue"in e?(this.he(t,30),t.we(As(e.bytesValue)),this._e(t)):"referenceValue"in e?this.me(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.he(t,45),t.le(r.latitude||0),t.le(r.longitude||0)):"mapValue"in e?Qs(e)?this.he(t,Number.MAX_SAFE_INTEGER):(this.ge(e.mapValue,t),this._e(t)):"arrayValue"in e?(this.ye(e.arrayValue,t),this._e(t)):br()}de(e,t){this.he(t,25),this.pe(e,t)}pe(e,t){t.fe(e)}ge(e,t){var n=e.fields||{};this.he(t,55);for(const e of Object.keys(n))this.de(e,t),this.ce(n[e],t)}ye(e,t){var n=e.values||[];this.he(t,50);for(const e of n)this.ce(e,t)}me(e,t){this.he(t,37),jr.fromName(e).path.forEach(e=>{this.he(t,60),this.pe(e,t)})}he(e,t){e.le(t)}_e(e){e.le(2)}}function yu(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}pu.Ie=new pu;class vu{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Te(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ee(n.value),n=t.next();this.Ae()}Re(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.be(n.value),n=t.next();this.Pe()}ve(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ee(e);else if(e<2048)this.Ee(960|e>>>6),this.Ee(128|63&e);else if(t<"\ud800"||"\udbff">>12),this.Ee(128|63&e>>>6),this.Ee(128|63&e);else{const e=t.codePointAt(0);this.Ee(240|e>>>18),this.Ee(128|63&e>>>12),this.Ee(128|63&e>>>6),this.Ee(128|63&e)}}this.Ae()}Ve(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.be(e);else if(e<2048)this.be(960|e>>>6),this.be(128|63&e);else if(t<"\ud800"||"\udbff">>12),this.be(128|63&e>>>6),this.be(128|63&e);else{const e=t.codePointAt(0);this.be(240|e>>>18),this.be(128|63&e>>>12),this.be(128|63&e>>>6),this.be(128|63&e)}}this.Pe()}Se(e){var t=this.De(e),n=yu(t);this.Ce(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r=this.Ke.length||!this.He(this.Ke[s++],e))return!1}return!0}We(e){for(const t of this.Ge)if(this.ze(t,e))return!0;return!1}ze(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}He(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function xu(e){if(0===e.getFilters().length)return[];const t=function t(e){if(Er(e instanceof Zs||e instanceof ei),e instanceof Zs)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=ei.create(n,e.op);return r=Ru(r),Cu(r)?r:(Er(r instanceof ei),Er(ti(r)),Er(1Nu(e,t)))}(function t(n){var e;if(Er(n instanceof Zs||n instanceof ei),n instanceof Zs){if(n instanceof di){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>Zs.create(n.field,"==",e)))||[];return ei.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return ei.create(r,n.op)}(e));return Er(Cu(t)),Du(t)||Au(t)?[t]:t.getFilters()}function Du(e){return e instanceof Zs}function Au(e){return e instanceof ei&&ri(e)}function Cu(e){return Du(e)||Au(e)||function(e){if(e instanceof ei&&ni(e)){for(const t of e.getFilters())if(!Du(t)&&!Au(t))return!1;return!0}return!1}(e)}function Nu(e,t){var n,r;return Er(e instanceof Zs||e instanceof ei),Er(t instanceof Zs||t instanceof ei),Ru(e instanceof Zs?t instanceof Zs?(n=e,r=t,ei.create([n,r],"and")):ku(e,t):t instanceof Zs?ku(t,e):function(e,t){if(Er(0Nu(e,r));return ei.create(s,"or")}(e,t))}function ku(t,e){if(ti(e))return ii(e,t.getFilters());var n=e.filters.map(e=>Nu(t,e));return ei.create(n,"or")}function Ru(t){if(Er(t instanceof Zs||t instanceof ei),t instanceof Zs)return t;const e=t.getFilters();if(1===e.length)return Ru(e[0]);if(si(t))return t;const n=e.map(e=>Ru(e)),r=[];return n.forEach(e=>{e instanceof Zs?r.push(e):e instanceof ei&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:ei.create(r,t.op)}class Lu{constructor(){this.Je=new Mu}addToCollectionParentIndex(e,t){return this.Je.add(t),rs.resolve()}getCollectionParents(e,t){return rs.resolve(this.Je.getEntries(t))}addFieldIndex(e,t){return rs.resolve()}deleteFieldIndex(e,t){return rs.resolve()}getDocumentsMatchingTarget(e,t){return rs.resolve(null)}getIndexType(e,t){return rs.resolve(0)}getFieldIndexes(e,t){return rs.resolve([])}getNextCollectionGroupToUpdate(e){return rs.resolve(null)}getMinOffset(e,t){return rs.resolve(Jr.min())}getMinOffsetFromCollectionGroup(e,t){return rs.resolve(Jr.min())}updateCollectionGroup(e,t,n){return rs.resolve()}updateIndexEntries(e,t){return rs.resolve()}}class Mu{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new wi(Ur.comparator),s=!r.has(n);return this.index[t]=r.add(n),s}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new wi(Ur.comparator)).toArray()}}const Fu=new Uint8Array(0);class Ou{constructor(e,t){this.user=e,this.databaseId=t,this.Ye=new Mu,this.Xe=new Aa(e=>Di(e),(e,t)=>Ai(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.Ye.has(t))return rs.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Ye.add(t)});r={collectionId:n,parent:bo(r)};return Vu(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[Vr(n),""],!1,!0);return Vu(e).W(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(To(t.parent))}return r})}addFieldIndex(e,t){const n=qu(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const s=n.add(r);if(t.indexState){const n=Bu(e);return s.next(e=>{n.put(hu(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return s.next()}deleteFieldIndex(e,t){const n=qu(e),r=Bu(e),s=Pu(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>s.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,c){const h=Pu(e);let l=!0;const n=new Map;return rs.forEach(this.Ze(c),t=>this.tn(e,t).next(e=>{l=l&&!!e,n.set(t,e)})).next(()=>{if(l){let u=Oa();const l=[];return rs.forEach(n,(e,t)=>{yr("IndexedDbIndexManager",`Using index ${o=e,`id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${Di(c)}`);var n=function(e,t){var n=Qr(t);if(void 0===n)return null;for(const t of Ni(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),r=function(e,t){const n=new Map;for(const r of zr(t))for(const t of Ni(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),s=function(e,t){const n=[];let r=!0;for(const s of zr(t)){const t=(0===s.kind?ki:Ri)(e,s.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new Hs(n,r)}(t,e),i=function(e,t){const n=[];let r=!0;for(const s of zr(t)){const t=(0===s.kind?Ri:ki)(e,s.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new Hs(n,r)}(t,e),a=this.en(e,t,s),o=this.en(e,t,i),r=this.nn(e,t,r),r=this.sn(e.indexId,n,a,s.inclusive,o,i.inclusive,r);return rs.forEach(r,e=>h.J(e,c.limit).next(e=>{e.forEach(e=>{var t=jr.fromSegments(e.documentKey);u.has(t)||(u=u.add(t),l.push(t))})}))}).next(()=>l)}return rs.resolve(null)})}Ze(t){let e=this.Xe.get(t);return e||(e=0===t.filters.length?[t]:xu(ei.create(t.filters,"and")).map(e=>xi(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.Xe.set(t,e),e)}sn(t,e,n,r,s,i,a){const o=(null!=e?e.length:1)*Math.max(n.length,s.length),u=o/(null!=e?e.length:1),c=[];for(let h=0;hthis.on(t,o,e,!0));c.push(...this.createRange(l,d,f))}return c}on(e,t,n,r){const s=new Eu(e,jr.empty(),t,n);return r?s:s.Ue()}un(e,t,n,r){const s=new Eu(e,jr.empty(),t,n);return r?s.Ue():s}tn(e,t){const r=new Su(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.je(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.Ze(t);return rs.forEach(r,t=>this.tn(e,t).next(e=>{e?0!==n&&e.fields.lengthnull!==t.limit&&1e instanceof Zs&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=qu(e),r=Bu(e);return(t?n.W("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.W()).next(e=>{const i=[];return rs.forEach(e,s=>r.get([s.indexId,this.uid]).next(e=>{var t,n,r;i.push((t=s,n=(e=e)?new Hr(e.sequenceNumber,new Jr(ru(e.readTime),new jr(To(e.documentKey)),e.largestBatchId)):Hr.empty(),r=t.fields.map(([e,t])=>new Wr(Kr.fromServerFormat(e),t)),new $r(t.indexId,t.collectionGroup,r,n)))})).next(()=>i)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:Fr(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const s=qu(e),i=Bu(e);return this.dn(e).next(t=>s.W("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>rs.forEach(e,e=>i.put(hu(e.indexId,this.user,t,r)))))}updateIndexEntries(s,e){const n=new Map;return rs.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?rs.resolve(e):this.getFieldIndexes(s,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),rs.forEach(e,n=>this._n(s,t,n).next(e=>{var t=this.wn(r,n);return e.isEqual(t)?rs.resolve():this.mn(s,r,n,e,t)}))))})}gn(e,t,n,r){return Pu(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.an(n,t.key),documentKey:t.key.path.toArray()})}yn(e,t,n,r){return Pu(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.an(n,t.key),t.key.path.toArray()])}_n(e,n,r){const t=Pu(e);let s=new wi(Tu);return t.Z({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.an(r,n)])},(e,t)=>{s=s.add(new Eu(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>s)}wn(e,t){let n=new wi(Tu);var r=this.cn(t,e);if(null==r)return n;const s=Qr(t);if(null!=s){var i=e.data.field(s.fieldPath);if(Us(i))for(const s of i.arrayValue.values||[])n=n.add(new Eu(t.indexId,e.key,this.rn(s),r))}else n=n.add(new Eu(t.indexId,e.key,Fu,r));return n}mn(t,n,r,c,e){yr("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,n,r,s){var i=c.getIterator(),a=e.getIterator();let o=bi(i),u=bi(a);for(;o||u;){let e=!1,t=!1;if(o&&u){const r=n(o,u);r<0?t=!0:0{s.push(this.gn(t,n,r,e))},e=>{s.push(this.yn(t,n,r,e))}),rs.waitFor(s)}dn(e){let r=1;return Bu(e).Z({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>Tu(e,t)).filter((e,t,n)=>!t||0!==Tu(e,n[t-1]));const r=[];r.push(e);for(const s of n){const n=Tu(s,e),i=Tu(s,t);if(0===n)r[0]=e.Ue();else if(0this.tn(t,e).next(e=>e||br())).next(Uu)}}function Vu(e){return Wo(e,"collectionParents")}function Pu(e){return Wo(e,"indexEntries")}function qu(e){return Wo(e,"indexConfiguration")}function Bu(e){return Wo(e,"indexState")}function Uu(e){Er(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let s=1;s(o++,n.delete()));i.push(u.next(()=>{Er(1===o)}));const c=[];for(const e of n.mutations){const r=xo(t,e.key.path,n.batchId);i.push(s.delete(r)),c.push(e.key)}return rs.waitFor(i).next(()=>c)}function $u(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw br();t=e.noDocument}return JSON.stringify(t).length}Ku.DEFAULT_COLLECTION_PERCENTILE=10,Ku.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Ku.DEFAULT=new Ku(41943040,Ku.DEFAULT_COLLECTION_PERCENTILE,Ku.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Ku.DISABLED=new Ku(-1,0,0);class Qu{constructor(e,t,n,r){this.userId=e,this.yt=t,this.indexManager=n,this.referenceDelegate=r,this.In={}}static re(e,t,n,r){Er(""!==e.uid);var s=e.isAuthenticated()?e.uid:"";return new Qu(s,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Wu(e).Z({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(h,l,d,f){const g=Hu(h),m=Wu(h);return m.add({}).next(e=>{Er("number"==typeof e);const t=new Ho(e,l,d,f),n=(s=this.yt,i=this.userId,a=t,o=a.baseMutations.map(e=>ho(s.ie,e)),u=a.mutations.map(e=>ho(s.ie,e)),{userId:i,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:u}),r=[];var s,i,a,o,u;let c=new wi((e,t)=>Fr(e.canonicalString(),t.canonicalString()));for(const h of f){const l=xo(this.userId,h.key.path,e);c=c.add(h.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,Do))}return c.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(h,e))}),h.addOnCommittedListener(()=>{this.In[e]=t.keys()}),rs.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return Wu(e).get(t).next(e=>e?(Er(e.userId===this.userId),su(this.yt,e)):null)}Tn(e,n){return this.In[n]?rs.resolve(this.In[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.In[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let s=null;return Wu(e).Z({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(Er(t.batchId>=r),s=su(this.yt,t)),n.done()}).next(()=>s)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return Wu(e).Z({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Wu(e).W("userMutationsIndex",t).next(e=>e.map(e=>su(this.yt,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=So(this.userId,o.path),t=IDBKeyRange.lowerBound(e),u=[];return Hu(a).Z({range:t},(e,t,n)=>{var[r,s,i]=e,s=To(s);if(r===this.userId&&o.path.isEqual(s))return Wu(a).get(i).next(e=>{if(!e)throw br();Er(e.userId===this.userId),u.push(su(this.yt,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new wi(Fr);const n=[];return e.forEach(a=>{var e=So(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=Hu(t).Z({range:e},(e,t,n)=>{var[r,s,i]=e,s=To(s);r===this.userId&&a.path.isEqual(s)?o=o.add(i):n.done()});n.push(e)}),rs.waitFor(n).next(()=>this.En(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=So(this.userId,a),r=IDBKeyRange.lowerBound(n);let u=new wi(Fr);return Hu(e).Z({range:r},(e,t,n)=>{var[r,s,i]=e,s=To(s);r===this.userId&&a.isPrefixOf(s)?s.length===o&&(u=u.add(i)):n.done()}).next(()=>this.En(e,u))}En(t,e){const n=[],r=[];return e.forEach(e=>{r.push(Wu(t).get(e).next(e=>{if(null===e)throw br();Er(e.userId===this.userId),n.push(su(this.yt,e))}))}),rs.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return ju(t.se,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.An(n.batchId)}),rs.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}An(e){delete this.In[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return rs.resolve();var t=IDBKeyRange.lowerBound([this.userId]);const r=[];return Hu(n).Z({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=To(e[1]);r.push(t)}else n.done()}).next(()=>{Er(0===r.length)})})}containsKey(e,t){return zu(e,this.userId,t)}Rn(e){return Yu(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function zu(e,i,t){const n=So(i,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return Hu(e).Z({range:r,X:!0},(e,t,n)=>{var[r,s]=e;r===i&&s===a&&(o=!0),n.done()}).next(()=>o)}function Wu(e){return Wo(e,"mutations")}function Hu(e){return Wo(e,"documentMutations")}function Yu(e){return Wo(e,"mutationQueues")}class Xu{constructor(e){this.bn=e}next(){return this.bn+=2,this.bn}static Pn(){return new Xu(0)}static vn(){return new Xu(-1)}}class Ju{constructor(e,t){this.referenceDelegate=e,this.yt=t}allocateTargetId(n){return this.Vn(n).next(e=>{const t=new Xu(e.highestTargetId);return e.highestTargetId=t.next(),this.Sn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Vn(e).next(e=>qr.fromTimestamp(new Pr(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Vn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.Vn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.Sn(t,e)))}addTargetData(t,n){return this.Dn(t,n).next(()=>this.Vn(t).next(e=>(e.targetCount+=1,this.Cn(n,e),this.Sn(t,e))))}updateTargetData(e,t){return this.Dn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Zu(t).delete(e.targetId)).next(()=>this.Vn(t)).next(e=>(Er(0{var n=iu(t);n.sequenceNumber<=s&&null===i.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>rs.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Zu(e).Z((e,t)=>{var n=iu(t);r(n)})}Vn(e){return ec(e).get("targetGlobalKey").next(e=>(Er(null!==e),e))}Sn(e,t){return ec(e).put("targetGlobalKey",t)}Dn(e,t){return Zu(e).put(au(this.yt,t))}Cn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Vn(e).next(e=>e.targetCount)}getTargetData(e,s){var t=Di(s),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let i=null;return Zu(e).Z({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=iu(t);Ai(s,r.target)&&(i=r,n.done())}).next(()=>i)}addMatchingKeys(n,e,r){const s=[],i=tc(n);return e.forEach(e=>{var t=bo(e.path);s.push(i.put({targetId:r,path:t})),s.push(this.referenceDelegate.addReference(n,r,e))}),rs.waitFor(s)}removeMatchingKeys(n,e,r){const s=tc(n);return rs.forEach(e,e=>{var t=bo(e.path);return rs.waitFor([s.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=tc(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=tc(e);let s=Oa();return r.Z({range:n,X:!0},(e,t,n)=>{var r=To(e[1]),r=new jr(r);s=s.add(r)}).next(()=>s)}containsKey(e,t){var n=bo(t.path),n=IDBKeyRange.bound([n],[Vr(n)],!1,!0);let r=0;return tc(e).Z({index:"documentTargetsIndex",X:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0e?iu(e):null)}}function Zu(e){return Wo(e,"targets")}function ec(e){return Wo(e,"targetGlobal")}function tc(e){return Wo(e,"targetDocuments")}function nc([e,t],[n,r]){var s=Fr(e,n);return 0===s?Fr(t,r):s}class rc{constructor(e){this.xn=e,this.buffer=new wi(nc),this.Nn=0}kn(){return++this.Nn}On(e){var t=[e,this.kn()];if(this.buffer.size{this.Mn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){us(e)?yr("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await ns(e)}await this.Fn(3e5)})}}class ic{constructor(e,t){this.$n=e,this.params=t}calculateTargetCount(e,t){return this.$n.Bn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return rs.resolve(ms.at);const n=new rc(t);return this.$n.forEachTarget(e,e=>n.On(e.sequenceNumber)).next(()=>this.$n.Ln(e,e=>n.On(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.$n.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.$n.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(yr("LruGarbageCollector","Garbage collection skipped; disabled"),rs.resolve(Gu)):this.getCacheSize(t).next(e=>e(s=e>this.params.maximumSequenceNumbersToCollect?(yr("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,s))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(i=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(c=Date.now(),pr()<=l.DEBUG&&yr("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-h}ms\n\tDetermined least recently used ${s} in `+(o-a)+"ms\n"+`\tRemoved ${i} targets in `+(u-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-u)+"ms\n"+`Total Duration: ${c-h}ms`),rs.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:e})))}}class ac{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new ic(e,t))}Bn(e){const n=this.Un(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Un(e){let t=0;return this.Ln(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Ln(e,n){return this.Kn(e,(e,t)=>n(t))}addReference(e,t,n){return oc(e,n)}removeReference(e,t,n){return oc(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return oc(e,t)}Gn(t,n){let r=!1;return Yu(t).tt(e=>zu(t,e,n).next(e=>(e&&(r=!0),rs.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const s=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[];let a=0;return this.Kn(n,(t,e)=>{if(e<=r){const r=this.Gn(n,t).next(e=>{if(!e)return a++,s.getEntry(n,t).next(()=>(s.removeEntry(t,qr.min()),tc(n).delete([0,bo(t.path)])))});i.push(r)}}).next(()=>rs.waitFor(i)).next(()=>s.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return oc(e,t)}Kn(e,r){const t=tc(e);let s,i=ms.at;return t.Z({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(i!==ms.at&&r(new jr(To(s)),i),i=n,s=t):i=ms.at}).next(()=>{i!==ms.at&&r(new jr(To(s)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function oc(e,t){return tc(e).put((e=e.currentSequenceNumber,{targetId:0,path:bo(t.path),sequenceNumber:e}))}class uc{constructor(){this.changes=new Aa(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,_i.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?rs.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class cc{constructor(e){this.yt=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return fc(e).put(n)}removeEntry(e,n,t){return fc(e).delete(function(e){const t=n.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],tu(e),t[t.length-1]]}(t))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Qn(t,e)))}getEntry(e,n){let r=_i.newInvalidDocument(n);return fc(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(gc(n))},(e,t)=>{r=this.jn(n,t)}).next(()=>r)}Wn(e,n){let r={size:0,document:_i.newInvalidDocument(n)};return fc(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(gc(n))},(e,t)=>{r={document:this.jn(n,t),size:$u(t)}}).next(()=>r)}getEntries(e,t){let r=Ca;return this.zn(e,t,(e,t)=>{var n=this.jn(e,t);r=r.insert(e,n)}).next(()=>r)}Hn(e,t){let r=Ca,s=new pi(jr.comparator);return this.zn(e,t,(e,t)=>{var n=this.jn(e,t);r=r.insert(e,n),s=s.insert(e,$u(t))}).next(()=>({documents:r,Jn:s}))}zn(e,t,s){if(t.isEmpty())return rs.resolve();let n=new wi(pc);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(gc(n.first()),gc(n.last())),i=n.getIterator();let a=i.getNext();return fc(e).Z({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=jr.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&pc(a,r)<0;)s(a,null),a=i.getNext();a&&a.isEqual(r)&&(s(a,t),a=i.hasNext()?i.getNext():null),a?n.j(gc(a)):n.done()}).next(()=>{for(;a;)s(a,null),a=i.hasNext()?i.getNext():null})}getDocumentsMatchingQuery(e,r,t,s){const n=r.path,i=[n.popLast().toArray(),n.lastSegment(),tu(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],a=[n.popLast().toArray(),n.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return fc(e).W(IDBKeyRange.bound(i,a,!0)).next(e=>{let t=Ca;for(const n of e){const e=this.jn(jr.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);e.isFoundDocument()&&(zi(r,e)||s.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,s){let i=Ca;var r=mc(t,n),a=mc(t,Jr.max());return fc(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.jn(jr.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);i=i.insert(r.key,r),i.size===s&&n.done()}).next(()=>i)}newChangeBuffer(e){return new lc(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return dc(e).get("remoteDocumentGlobalKey").next(e=>(Er(!!e),e))}Qn(e,t){return dc(e).put("remoteDocumentGlobalKey",t)}jn(e,t){if(t){const e=function(e,t){let n;if(t.document)n=co(e.ie,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=jr.fromSegments(t.noDocument.path),s=ru(t.noDocument.readTime);n=_i.newNoDocument(e,s),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return br();{const e=jr.fromSegments(t.unknownDocument.path),i=ru(t.unknownDocument.version);n=_i.newUnknownDocument(e,i)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new Pr(t[0],t[1]),qr.fromTimestamp(r))),n;var r}(this.yt,t);if(!e.isNoDocument()||!e.version.isEqual(qr.min()))return e}return _i.newInvalidDocument(e)}}function hc(e){return new cc(e)}class lc extends uc{constructor(e,t){super(),this.Yn=e,this.trackRemovals=t,this.Xn=new Aa(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(i){const a=[];let o=0,u=new wi((e,t)=>Fr(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Xn.get(e);if(a.push(this.Yn.removeEntry(i,e,n.readTime)),t.isValidDocument()){var r=eu(this.Yn.yt,t);u=u.add(e.path.popLast());var s=$u(r);o+=s-n.size,a.push(this.Yn.addEntry(i,e,r))}else if(o-=n.size,this.trackRemovals){const o=eu(this.Yn.yt,t.convertToNoDocument(qr.min()));a.push(this.Yn.addEntry(i,e,o))}}),u.forEach(e=>{a.push(this.Yn.indexManager.addToCollectionParentIndex(i,e))}),a.push(this.Yn.updateMetadata(i,o)),rs.waitFor(a)}getFromCache(e,t){return this.Yn.Wn(e,t).next(e=>(this.Xn.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Yn.Hn(e,t).next(({documents:n,Jn:e})=>(e.forEach((e,t)=>{this.Xn.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function dc(e){return Wo(e,"remoteDocumentGlobal")}function fc(e){return Wo(e,"remoteDocumentsV14")}function gc(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function mc(e,t){const n=t.documentKey.path.toArray();return[e,tu(t.readTime),n.slice(0,n.length-2),0(r=e,this.remoteDocumentCache.getEntry(t,n))).next(e=>(null!==r&&pa(r.mutation,e,Ei.empty(),Pr.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,Oa()).next(()=>e))}getLocalViewOfDocuments(e,t,n=Oa()){const r=La();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=ka();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=La();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,Oa()))}populateOverlays(e,n,t){const r=[];return t.forEach(e=>{n.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,t)=>{n.set(e,t)})})}computeViews(e,t,r,s){let i=Ca;const a=La(),o=La();return t.forEach((e,t)=>{const n=r.get(t.key);s.has(t.key)&&(void 0===n||n.mutation instanceof wa)?i=i.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),pa(n.mutation,t,n.mutation.getFieldMask(),Pr.now())):a.set(t.key,Ei.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new yc(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(i,a){const o=La();let u=new pi((e,t)=>e-t),c=Oa();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(i,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||Ei.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(u.get(r.batchId)||Oa()).add(e),u=u.insert(r.batchId,t))})}).next(()=>{const e=[],t=u.getReverseIterator();for(;t.hasNext();){const u=t.getNext(),n=u.key,r=u.value,s=La();r.forEach(e=>{var t;c.has(e)||(null!==(t=ga(a.get(e),o.get(e)))&&s.set(e,t),c=c.add(e))}),e.push(this.documentOverlayCache.saveOverlays(i,n,s))}return rs.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,jr.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):qi(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n);var r}getNextDocuments(i,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(i,t,a,o).next(n=>{const e=0rs.forEach(e,(t,e)=>(r{s=s.insert(t,e)}))).next(()=>this.populateOverlays(i,e,n)).next(()=>this.computeViews(i,s,e,Oa())).next(e=>({batchId:r,changes:Ra(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new jr(t)).next(e=>{let t=ka();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,s,i){const a=s.collectionGroup;let o=ka();return this.indexManager.getCollectionParents(r,a).next(e=>rs.forEach(e,e=>{var t,n=(t=s,e=e.child(a),new Li(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,i).next(e=>{e.forEach((e,t)=>{o=o.insert(e,t)})})}).next(()=>o))}getDocumentsMatchingCollectionQuery(t,i,n){let a;return this.documentOverlayCache.getOverlaysForCollection(t,i.path,n.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,i,n,a))).next(r=>{a.forEach((e,t)=>{var n=t.getKey();null===r.get(n)&&(r=r.insert(n,_i.newInvalidDocument(n)))});let s=ka();return r.forEach((e,t)=>{var n=a.get(e);void 0!==n&&pa(n.mutation,t,Ei.empty(),Pr.now()),zi(i,t)&&(s=s.insert(e,t))}),s})}}class wc{constructor(e){this.yt=e,this.Zn=new Map,this.ts=new Map}getBundleMetadata(e,t){return rs.resolve(this.Zn.get(t))}saveBundleMetadata(e,t){return this.Zn.set(t.id,{id:t.id,version:t.version,createTime:Za(t.createTime)}),rs.resolve()}getNamedQuery(e,t){return rs.resolve(this.ts.get(t))}saveNamedQuery(e,t){return this.ts.set(t.name,{name:(t=t).name,query:ou(t.bundledQuery),readTime:Za(t.readTime)}),rs.resolve()}}class Ic{constructor(){this.overlays=new pi(jr.comparator),this.es=new Map}getOverlay(e,t){return rs.resolve(this.overlays.get(t))}getOverlays(e,t){const n=La();return rs.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.oe(n,r,t)}),rs.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.es.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.es.delete(n)),rs.resolve()}getOverlaysForCollection(e,t,n){const r=La(),s=t.length+1,i=new jr(t.child("")),a=this.overlays.getIteratorFrom(i);for(;a.hasNext();){const e=a.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===s&&e.largestBatchId>n&&r.set(e.getKey(),e)}return rs.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let s=new pi((e,t)=>e-t);const i=this.overlays.getIterator();for(;i.hasNext();){const t=i.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=s.get(t.largestBatchId);null===e&&(e=La(),s=s.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=La(),o=s.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return rs.resolve(a)}oe(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.es.get(r.largestBatchId).delete(n.key);this.es.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new Xo(t,n));let s=this.es.get(t);void 0===s&&(s=Oa(),this.es.set(t,s)),this.es.set(t,s.add(n.key))}}class bc{constructor(){this.ns=new wi(Ec.ss),this.rs=new wi(Ec.os)}isEmpty(){return this.ns.isEmpty()}addReference(e,t){var n=new Ec(e,t);this.ns=this.ns.add(n),this.rs=this.rs.add(n)}us(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.cs(new Ec(e,t))}hs(e,t){e.forEach(e=>this.removeReference(e,t))}ls(e){const t=new jr(new Ur([])),n=new Ec(t,e),r=new Ec(t,e+1),s=[];return this.rs.forEachInRange([n,r],e=>{this.cs(e),s.push(e.key)}),s}fs(){this.ns.forEach(e=>this.cs(e))}cs(e){this.ns=this.ns.delete(e),this.rs=this.rs.delete(e)}ds(e){var t=new jr(new Ur([])),n=new Ec(t,e),t=new Ec(t,e+1);let r=Oa();return this.rs.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Ec(e,0),t=this.ns.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Ec{constructor(e,t){this.key=e,this._s=t}static ss(e,t){return jr.comparator(e.key,t.key)||Fr(e._s,t._s)}static os(e,t){return Fr(e._s,t._s)||jr.comparator(e.key,t.key)}}class Tc{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.ws=1,this.gs=new wi(Ec.ss)}checkEmpty(e){return rs.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var s=this.ws;this.ws++,0n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return rs.resolve(0===this.mutationQueue.length?-1:this.ws-1)}getAllMutationBatches(e){return rs.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Ec(t,0),r=new Ec(t,Number.POSITIVE_INFINITY),s=[];return this.gs.forEachInRange([n,r],e=>{var t=this.ys(e._s);s.push(t)}),rs.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new wi(Fr);return t.forEach(e=>{var t=new Ec(e,0),n=new Ec(e,Number.POSITIVE_INFINITY);this.gs.forEachInRange([t,n],e=>{r=r.add(e._s)})}),rs.resolve(this.Is(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let s=n;jr.isDocumentKey(s)||(s=s.child(""));var i=new Ec(new jr(s),0);let a=new wi(Fr);return this.gs.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e._s)),!0)},i),rs.resolve(this.Is(a))}Is(e){const n=[];return e.forEach(e=>{var t=this.ys(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Er(0===this.Ts(r.batchId,"removed")),this.mutationQueue.shift();let s=this.gs;return rs.forEach(r.mutations,e=>{var t=new Ec(e.key,r.batchId);return s=s.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.gs=s})}An(e){}containsKey(e,t){var n=new Ec(t,0),n=this.gs.firstAfterOrEqual(n);return rs.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,rs.resolve()}Ts(e,t){return this.ps(e)}ps(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}ys(e){var t=this.ps(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class _c{constructor(e){this.Es=e,this.docs=new pi(jr.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),s=r?r.size:0,i=this.Es(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-s,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return rs.resolve(n?n.document.mutableCopy():_i.newInvalidDocument(t))}getEntries(e,t){let n=Ca;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():_i.newInvalidDocument(e))}),rs.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let s=Ca;const i=t.path,a=new jr(i.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!i.isPrefixOf(e.path))break;e.path.length>i.length+1||Zr(Xr(a),n)<=0||(r.has(a.key)||zi(t,a))&&(s=s.insert(a.key,a.mutableCopy()))}return rs.resolve(s)}getAllFromCollectionGroup(e,t,n,r){br()}As(e,t){return rs.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new Sc(this)}getSize(e){return rs.resolve(this.size)}}class Sc extends uc{constructor(e){super(),this.Yn=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.Yn.addEntry(n,t)):this.Yn.removeEntry(e)}),rs.waitFor(r)}getFromCache(e,t){return this.Yn.getEntry(e,t)}getAllFromCache(e,t){return this.Yn.getEntries(e,t)}}class xc{constructor(e){this.persistence=e,this.Rs=new Aa(e=>Di(e),Ai),this.lastRemoteSnapshotVersion=qr.min(),this.highestTargetId=0,this.bs=0,this.Ps=new bc,this.targetCount=0,this.vs=Xu.Pn()}forEachTarget(e,n){return this.Rs.forEach((e,t)=>n(t)),rs.resolve()}getLastRemoteSnapshotVersion(e){return rs.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return rs.resolve(this.bs)}allocateTargetId(e){return this.highestTargetId=this.vs.next(),rs.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.bs&&(this.bs=t),rs.resolve()}Dn(e){this.Rs.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.vs=new Xu(t),this.highestTargetId=t),e.sequenceNumber>this.bs&&(this.bs=e.sequenceNumber)}addTargetData(e,t){return this.Dn(t),this.targetCount+=1,rs.resolve()}updateTargetData(e,t){return this.Dn(t),rs.resolve()}removeTargetData(e,t){return this.Rs.delete(t.target),this.Ps.ls(t.targetId),--this.targetCount,rs.resolve()}removeTargets(n,r,s){let i=0;const a=[];return this.Rs.forEach((e,t)=>{t.sequenceNumber<=r&&null===s.get(t.targetId)&&(this.Rs.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),i++)}),rs.waitFor(a).next(()=>i)}getTargetCount(e){return rs.resolve(this.targetCount)}getTargetData(e,t){var n=this.Rs.get(t)||null;return rs.resolve(n)}addMatchingKeys(e,t,n){return this.Ps.us(t,n),rs.resolve()}removeMatchingKeys(t,e,n){this.Ps.hs(e,n);const r=this.persistence.referenceDelegate,s=[];return r&&e.forEach(e=>{s.push(r.markPotentiallyOrphaned(t,e))}),rs.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.Ps.ls(t),rs.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Ps.ds(t);return rs.resolve(n)}containsKey(e,t){return rs.resolve(this.Ps.containsKey(t))}}class Dc{constructor(e,t){this.Vs={},this.overlays={},this.Ss=new ms(0),this.Ds=!1,this.Ds=!0,this.referenceDelegate=e(this),this.Cs=new xc(this),this.indexManager=new Lu,this.remoteDocumentCache=(e=e=>this.referenceDelegate.xs(e),new _c(e)),this.yt=new Zo(t),this.Ns=new wc(this.yt)}start(){return Promise.resolve()}shutdown(){return this.Ds=!1,Promise.resolve()}get started(){return this.Ds}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Ic,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Vs[e.toKey()];return n||(n=new Tc(t,this.referenceDelegate),this.Vs[e.toKey()]=n),n}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ns}runTransaction(e,t,n){yr("MemoryPersistence","Starting transaction:",e);const r=new Ac(this.Ss.next());return this.referenceDelegate.ks(),n(r).next(e=>this.referenceDelegate.Os(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ms(t,n){return rs.or(Object.values(this.Vs).map(e=>()=>e.containsKey(t,n)))}}class Ac extends ts{constructor(e){super(),this.currentSequenceNumber=e}}class Cc{constructor(e){this.persistence=e,this.Fs=new bc,this.$s=null}static Bs(e){return new Cc(e)}get Ls(){if(this.$s)return this.$s;throw br()}addReference(e,t,n){return this.Fs.addReference(n,t),this.Ls.delete(n.toString()),rs.resolve()}removeReference(e,t,n){return this.Fs.removeReference(n,t),this.Ls.add(n.toString()),rs.resolve()}markPotentiallyOrphaned(e,t){return this.Ls.add(t.toString()),rs.resolve()}removeTarget(e,t){this.Fs.ls(t.targetId).forEach(e=>this.Ls.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Ls.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}ks(){this.$s=new Set}Os(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return rs.forEach(this.Ls,e=>{const t=jr.fromPath(e);return this.qs(n,t).next(e=>{e||r.removeEntry(t,qr.min())})}).next(()=>(this.$s=null,r.apply(n)))}updateLimboDocument(e,t){return this.qs(e,t).next(e=>{e?this.Ls.delete(t.toString()):this.Ls.add(t.toString())})}xs(e){return 0}qs(e,t){return rs.or([()=>rs.resolve(this.Fs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ms(e,t)])}}class Nc{constructor(e){this.yt=e}$(t,e,n,r){const s=new ss("createOrUpgrade",e);var i;n<1&&1<=r&&(t.createObjectStore("owner"),(i=t).createObjectStore("mutationQueues",{keyPath:"userId"}),i.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",_o,{unique:!0}),i.createObjectStore("documentMutations"),kc(t),t.createObjectStore("remoteDocuments"));let a=rs.resolve();return n<3&&3<=r&&(0!==n&&((i=t).deleteObjectStore("targetDocuments"),i.deleteObjectStore("targets"),i.deleteObjectStore("targetGlobal"),kc(t)),a=a.next(()=>function(){const e=s.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:qr.min().toTimestamp(),targetCount:0};return e.put("targetGlobalKey",t)}())),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,s){return s.store("mutations").W().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",_o,{unique:!0});const t=s.store("mutations"),n=e.map(e=>t.put(e));return rs.waitFor(n)})}(t,s))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.Us(s))),n<6&&6<=r&&(a=a.next(()=>(t.createObjectStore("remoteDocumentGlobal"),this.Ks(s)))),n<7&&7<=r&&(a=a.next(()=>this.Gs(s))),n<8&&8<=r&&(a=a.next(()=>this.Qs(t,s))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.js(s))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(){const e=t.createObjectStore("documentOverlays",{keyPath:qo});e.createIndex("collectionPathOverlayIndex",Bo,{unique:!1}),e.createIndex("collectionGroupOverlayIndex",Uo,{unique:!1})}()})),n<13&&13<=r&&(a=a.next(()=>function(){const e=t.createObjectStore("remoteDocumentsV14",{keyPath:Ao});e.createIndex("documentKeyIndex",Co),e.createIndex("collectionGroupIndex",No)}()).next(()=>this.Ws(t,s)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.zs(t,s))),n<15&&15<=r&&(a=a.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Fo}).createIndex("sequenceNumberIndex",Oo,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Vo}).createIndex("documentKeyIndex",Po,{unique:!1})}(t))),a}Ks(t){let n=0;return t.store("remoteDocuments").Z((e,t)=>{n+=$u(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Us(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.W().next(e=>rs.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.W("userMutationsIndex",e).next(e=>rs.forEach(e,e=>{Er(e.userId===n.userId);var t=su(this.yt,e);return ju(r,n.userId,t).next(()=>{})}))}))}Gs(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(s=>{const i=[];return t.Z((e,t)=>{const n=new Ur(e),r=[0,bo(n)];i.push(a.get(r).next(e=>e?rs.resolve():(e=>a.put({targetId:0,path:bo(e),sequenceNumber:s.highestListenSequenceNumber}))(n)))}).next(()=>rs.waitFor(i))})}Qs(e,t){e.createObjectStore("collectionParents",{keyPath:Mo});const n=t.store("collectionParents"),r=new Mu,s=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:bo(r)})}};return t.store("remoteDocuments").Z({X:!0},(e,t)=>{const n=new Ur(e);return s(n.popLast())}).next(()=>t.store("documentMutations").Z({X:!0},([,e],t)=>{const n=To(e);return s(n.popLast())}))}js(e){const r=e.store("targets");return r.Z((e,t)=>{var n=iu(t),n=au(this.yt,n);return r.put(n)})}Ws(e,i){const t=i.store("remoteDocuments"),a=[];return t.Z((e,t)=>{const n=i.store("remoteDocumentsV14"),r=((s=t).document?new jr(Ur.fromString(s.document.name).popFirst(5)):s.noDocument?jr.fromSegments(s.noDocument.path):s.unknownDocument?jr.fromSegments(s.unknownDocument.path):br()).path.toArray();var s={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};a.push(n.put(s))}).next(()=>rs.waitFor(a))}zs(e,i){const t=i.store("mutations"),a=hc(this.yt),o=new Dc(Cc.Bs,this.yt.ie);return t.W().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:Oa();su(this.yt,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),rs.forEach(r,(e,t)=>{var n=new fr(t),r=gu.re(this.yt,n),s=o.getIndexManager(n),n=Qu.re(n,this.yt,s,o.referenceDelegate);return new vc(a,n,r,s).recalculateAndSaveOverlaysForDocumentKeys(new zo(i,ms.at),e).next()})})}}function kc(e){e.createObjectStore("targetDocuments",{keyPath:Ro}).createIndex("documentTargetsIndex",Lo,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",ko,{unique:!0}),e.createObjectStore("targetGlobal")}const Rc="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class Lc{constructor(e,t,n,r,s,i,a,o,u,c,h=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Hs=s,this.window=i,this.document=a,this.Js=u,this.Ys=c,this.Xs=h,this.Ss=null,this.Ds=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Zs=null,this.inForeground=!1,this.ti=null,this.ei=null,this.ni=Number.NEGATIVE_INFINITY,this.si=e=>Promise.resolve(),!Lc.C())throw new _r(Tr.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new ac(this,r),this.ii=t+"main",this.yt=new Zo(o),this.ri=new is(this.ii,this.Xs,new Nc(this.yt)),this.Cs=new Ju(this.referenceDelegate,this.yt),this.remoteDocumentCache=hc(this.yt),this.Ns=new lu,this.window&&this.window.localStorage?this.oi=this.window.localStorage:(this.oi=null,!1===c&&vr("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.ui().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new _r(Tr.FAILED_PRECONDITION,Rc);return this.ci(),this.ai(),this.hi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Cs.getHighestSequenceNumber(e))}).then(e=>{this.Ss=new ms(e,this.Js)}).then(()=>{this.Ds=!0}).catch(e=>(this.ri&&this.ri.close(),Promise.reject(e)))}li(t){return this.si=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ri.L(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Hs.enqueueAndForget(async()=>{this.started&&await this.ui()}))}ui(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>Fc(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.fi(t).next(e=>{e||(this.isPrimary=!1,this.Hs.enqueueRetryable(()=>this.si(!1)))})}).next(()=>this.di(t)).next(e=>this.isPrimary&&!e?this._i(t).next(()=>!1):!!e&&this.wi(t).next(()=>!0))).catch(e=>{if(us(e))return yr("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return yr("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Hs.enqueueRetryable(()=>this.si(e)),this.isPrimary=e})}fi(e){return Mc(e).get("owner").next(e=>rs.resolve(this.mi(e)))}gi(e){return Fc(e).delete(this.clientId)}async yi(){if(this.isPrimary&&!this.pi(this.ni,18e5)){this.ni=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=Wo(e,"clientMetadata");return r.W().next(e=>{const t=this.Ii(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return rs.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.oi)for(const t of e)this.oi.removeItem(this.Ti(t.clientId))}}hi(){this.ei=this.Hs.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.ui().then(()=>this.yi()).then(()=>this.hi()))}mi(e){return!!e&&e.ownerId===this.clientId}di(t){return this.Ys?rs.resolve(!0):Mc(t).get("owner").next(e=>{if(null!==e&&this.pi(e.leaseTimestampMs,5e3)&&!this.Ei(e.ownerId)){if(this.mi(e)&&this.networkEnabled)return!0;if(!this.mi(e)){if(!e.allowTabSynchronization)throw new _r(Tr.FAILED_PRECONDITION,Rc);return!1}}return!(!this.networkEnabled||!this.inForeground)||Fc(t).W().next(e=>void 0===this.Ii(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&yr("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Ds=!1,this.Ai(),this.ei&&(this.ei.cancel(),this.ei=null),this.Ri(),this.bi(),await this.ri.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new zo(e,ms.at);return this._i(t).next(()=>this.gi(t))}),this.ri.close(),this.Pi()}Ii(e,t){return e.filter(e=>this.pi(e.updateTimeMs,t)&&!this.Ei(e.clientId))}vi(){return this.runTransaction("getActiveClients","readonly",e=>Fc(e).W().next(e=>this.Ii(e,18e5).map(e=>e.clientId)))}get started(){return this.Ds}getMutationQueue(e,t){return Qu.re(e,this.yt,t,this.referenceDelegate)}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new Ou(e,this.yt.ie.databaseId)}getDocumentOverlayCache(e){return gu.re(this.yt,e)}getBundleCache(){return this.Ns}runTransaction(t,n,r){yr("IndexedDbPersistence","Starting transaction:",t);var e,s="readonly"===n?"readonly":"readwrite",e=15===(e=this.Xs)?Qo:14===e?$o:13===e?jo:12===e?Ko:11===e?Go:void br();let i;return this.ri.runTransaction(t,s,e,e=>(i=new zo(e,this.Ss?this.Ss.next():ms.at),"readwrite-primary"===n?this.fi(i).next(e=>!!e||this.di(i)).next(e=>{if(!e)throw vr(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Hs.enqueueRetryable(()=>this.si(!1)),new _r(Tr.FAILED_PRECONDITION,es);return r(i)}).next(e=>this.wi(i).next(()=>e)):this.Vi(i).next(()=>r(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Vi(e){return Mc(e).get("owner").next(e=>{if(null!==e&&this.pi(e.leaseTimestampMs,5e3)&&!this.Ei(e.ownerId)&&!this.mi(e)&&!(this.Ys||this.allowTabSynchronization&&e.allowTabSynchronization))throw new _r(Tr.FAILED_PRECONDITION,Rc)})}wi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return Mc(e).put("owner",t)}static C(){return is.C()}_i(e){const t=Mc(e);return t.get("owner").next(e=>this.mi(e)?(yr("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):rs.resolve())}pi(e,t){var n=Date.now();return!(e ${n}`),1))}ci(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ti=()=>{this.Hs.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.ui()))},this.document.addEventListener("visibilitychange",this.ti),this.inForeground="visible"===this.document.visibilityState)}Ri(){this.ti&&(this.document.removeEventListener("visibilitychange",this.ti),this.ti=null)}ai(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Zs=()=>{this.Ai(),c()&&navigator.appVersion.match(/Version\/1[45]/)&&this.Hs.enterRestrictedMode(!0),this.Hs.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Zs))}bi(){this.Zs&&(this.window.removeEventListener("pagehide",this.Zs),this.Zs=null)}Ei(e){var t;try{var n=null!==(null===(t=this.oi)||void 0===t?void 0:t.getItem(this.Ti(e)));return yr("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return vr("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Ai(){if(this.oi)try{this.oi.setItem(this.Ti(this.clientId),String(Date.now()))}catch(e){vr("Failed to set zombie client id.",e)}}Pi(){if(this.oi)try{this.oi.removeItem(this.Ti(this.clientId))}catch(e){}}Ti(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function Mc(e){return Wo(e,"owner")}function Fc(e){return Wo(e,"clientMetadata")}function Oc(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class Vc{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Si=n,this.Di=r}static Ci(e,t){let n=Oa(),r=Oa();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new Vc(e,t.fromCache,n,r)}}class Pc{constructor(){this.xi=!1}initialize(e,t){this.Ni=e,this.indexManager=t,this.xi=!0}getDocumentsMatchingQuery(t,n,r,s){return this.ki(t,n).next(e=>e||this.Oi(t,n,s,r)).next(e=>e||this.Mi(t,n))}ki(s,i){if(Oi(i))return rs.resolve(null);let t=Ui(i);return this.indexManager.getIndexType(s,t).next(e=>0===e?null:(null!==i.limit&&1===e&&(i=Ki(i,null,"F"),t=Ui(i)),this.indexManager.getDocumentsMatchingTarget(s,t).next(e=>{const r=Oa(...e);return this.Ni.getDocuments(s,r).next(n=>this.indexManager.getMinOffset(s,t).next(e=>{var t=this.Fi(i,n);return this.$i(i,t,r,e.readTime)?this.ki(s,Ki(i,null,"F")):this.Bi(s,t,i,e)}))})))}Oi(n,r,s,i){return Oi(r)||i.isEqual(qr.min())?this.Mi(n,r):this.Ni.getDocuments(n,s).next(e=>{var t=this.Fi(r,e);return this.$i(r,t,s,i)?this.Mi(n,r):(pr()<=l.DEBUG&&yr("QueryEngine","Re-using previous result from %s to execute query: %s",i.toString(),Qi(r)),this.Bi(n,t,r,Yr(i,-1)))})}Fi(n,e){let r=new wi(Hi(n));return e.forEach((e,t)=>{zi(n,t)&&(r=r.add(t))}),r}$i(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const s="F"===e.limitType?t.last():t.first();return!!s&&(s.hasPendingWrites||0(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class qc{constructor(e,t,n,r){this.persistence=e,this.Li=t,this.yt=r,this.qi=new pi(Fr),this.Ui=new Aa(e=>Di(e),Ai),this.Ki=new Map,this.Gi=e.getRemoteDocumentCache(),this.Cs=e.getTargetCache(),this.Ns=e.getBundleCache(),this.Qi(n)}Qi(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new vc(this.Gi,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Gi.setIndexManager(this.indexManager),this.Li.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.qi))}}function Bc(e,t,n,r){return new qc(e,t,n,r)}async function Uc(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",s=>{let i;return a.mutationQueue.getAllMutationBatches(s).next(e=>(i=e,a.Qi(t),a.mutationQueue.getAllMutationBatches(s))).next(e=>{const t=[],n=[];let r=Oa();for(const s of i){t.push(s.batchId);for(const e of s.mutations)r=r.add(e.key)}for(const s of e){n.push(s.batchId);for(const e of s.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(s,r).next(e=>({ji:e,removedBatchIds:t,addedBatchIds:n}))})})}function Gc(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Cs.getLastRemoteSnapshotVersion(e))}function Kc(e,c){const h=e,l=c.snapshotVersion;let d=h.qi;return h.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=h.Gi.newChangeBuffer({trackRemovals:!0});d=h.qi;const u=[];c.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(h.Cs.removeMatchingKeys(o,t.removedDocuments,n).next(()=>h.Cs.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var s,i,a;c.targetMismatches.has(n)?e=e.withResumeToken(_s.EMPTY_BYTE_STRING,qr.min()).withLastLimboFreeSnapshotVersion(qr.min()):0{c.resolvedLimboDocuments.has(e)&&u.push(h.persistence.referenceDelegate.updateLimboDocument(o,e))}),u.push(jc(o,e,c.documentUpdates).next(e=>{t=e.Wi,n=e.zi})),!l.isEqual(qr.min())){const c=h.Cs.getLastRemoteSnapshotVersion(o).next(e=>h.Cs.setTargetsMetadata(o,o.currentSequenceNumber,l));u.push(c)}return rs.waitFor(u).next(()=>e.apply(o)).next(()=>h.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(h.qi=d,e))}function jc(e,i,t){let n=Oa(),a=Oa();return t.forEach(e=>n=n.add(e)),i.getEntries(e,n).next(r=>{let s=Ca;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(qr.min())?(i.removeEntry(e,t.readTime),s=s.insert(e,t)):!n.isValidDocument()||0{let n;return s.Cs.getTargetData(t,r).next(e=>e?(n=e,rs.resolve(n)):s.Cs.allocateTargetId(t).next(e=>(n=new Jo(r,e,0,t.currentSequenceNumber),s.Cs.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=s.qi.get(e.targetId);return(null===t||0r.persistence.referenceDelegate.removeTarget(e,s))}catch(e){if(!us(e))throw e;yr("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.qi=r.qi.remove(t),r.Ui.delete(s.target)}function zc(e,n,r){const s=e;let i=qr.min(),a=Oa();return s.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,s=r.Ui.get(n);return void 0!==s?rs.resolve(r.qi.get(s)):r.Cs.getTargetData(t,n)}(s,t,Ui(n)).next(e=>{if(e)return i=e.lastLimboFreeSnapshotVersion,s.Cs.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>s.Li.getDocumentsMatchingQuery(t,n,r?i:qr.min(),r?a:Oa())).next(e=>(Yc(s,Wi(n),e),{documents:e,Hi:a})))}function Wc(e,t){const n=e,r=n.Cs,s=n.qi.get(t);return s?Promise.resolve(s.target):n.persistence.runTransaction("Get target data","readonly",e=>r.ne(e,t).next(e=>e?e.target:null))}function Hc(e,t){const n=e,r=n.Ki.get(t)||qr.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.Gi.getAllFromCollectionGroup(e,t,Yr(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(Yc(n,t,e),e))}function Yc(e,t,n){let r=e.Ki.get(t)||qr.min();n.forEach((e,t)=>{0this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.hr,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Ir(this.ur)}isActiveQueryTarget(n){let r=!1;return this.ur.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Tr(e,"pending")}updateMutationState(e,t,n){this.Tr(e,t,n),this.Er(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Zc(this.persistenceKey,e)))||(n=th.Zi(e,n))&&(t=n.state)),this.Ar.er(e),this.gr(),t}removeLocalQueryTarget(e){this.Ar.nr(e),this.gr()}isLocalQueryTarget(e){return this.Ar.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Zc(this.persistenceKey,e))}updateQueryState(e,t,n){this.Rr(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Er(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.br(e)}notifyBundleLoaded(e){this.Pr(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ir),this.removeItem(this.ar),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return yr("SharedClientState","READ",e,t),t}setItem(e,t){yr("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){yr("SharedClientState","REMOVE",e),this.storage.removeItem(e)}rr(e){const s=e;s.storageArea===this.storage&&(yr("SharedClientState","EVENT",s.key,s.newValue),s.key!==this.ar?this.Hs.enqueueRetryable(async()=>{if(this.started){if(null!==s.key)if(this.lr.test(s.key)){if(null==s.newValue){var e=this.vr(s.key);return this.Vr(e,null)}e=this.Sr(s.key,s.newValue);if(e)return this.Vr(e.clientId,e)}else if(this.dr.test(s.key)){if(null!==s.newValue){var t=this.Dr(s.key,s.newValue);if(t)return this.Cr(t)}}else if(this._r.test(s.key)){if(null!==s.newValue){t=this.Nr(s.key,s.newValue);if(t)return this.kr(t)}}else if(s.key===this.wr){if(null!==s.newValue){var n=this.yr(s.newValue);if(n)return this.pr(n)}}else if(s.key===this.hr){n=function(e){let t=ms.at;if(null!=e)try{var n=JSON.parse(e);Er("number"==typeof n),t=n}catch(e){vr("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(s.newValue);n!==ms.at&&this.sequenceNumberHandler(n)}else if(s.key===this.mr){const r=this.Or(s.newValue);await Promise.all(r.map(e=>this.syncEngine.Mr(e)))}}else this.cr.push(s)}):vr("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Ar(){return this.ur.get(this.sr)}gr(){this.setItem(this.ar,this.Ar.tr())}Tr(e,t,n){const r=new eh(this.currentUser,e,t,n),s=Jc(this.persistenceKey,this.currentUser,e);this.setItem(s,r.tr())}Er(e){var t=Jc(this.persistenceKey,this.currentUser,e);this.removeItem(t)}br(e){var t={clientId:this.sr,onlineState:e};this.storage.setItem(this.wr,JSON.stringify(t))}Rr(e,t,n){const r=Zc(this.persistenceKey,e),s=new th(e,t,n);this.setItem(r,s.tr())}Pr(e){var t=JSON.stringify(Array.from(e));this.setItem(this.mr,t)}vr(e){var t=this.lr.exec(e);return t?t[1]:null}Sr(e,t){var n=this.vr(e);return nh.Zi(n,t)}Dr(e,t){var n=this.dr.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return eh.Zi(new fr(n),r,t)}Nr(e,t){var n=this._r.exec(e),n=Number(n[1]);return th.Zi(n,t)}yr(e){return rh.Zi(e)}Or(e){return JSON.parse(e)}async Cr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Fr(e.batchId,e.state,e.error);yr("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}kr(e){return this.syncEngine.$r(e.targetId,e.state,e.error)}Vr(e,t){const n=t?this.ur.insert(e,t):this.ur.remove(e),r=this.Ir(this.ur),s=this.Ir(n),i=[],a=[];return s.forEach(e=>{r.has(e)||i.push(e)}),r.forEach(e=>{s.has(e)||a.push(e)}),this.syncEngine.Br(i,a).then(()=>{this.ur=n})}pr(e){this.ur.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Ir(e){let n=Va;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class ah{constructor(){this.Lr=new sh,this.qr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Lr.er(e),this.qr[e]||"not-current"}updateQueryState(e,t,n){this.qr[e]=t}removeLocalQueryTarget(e){this.Lr.nr(e)}isLocalQueryTarget(e){return this.Lr.activeTargetIds.has(e)}clearQueryState(e){delete this.qr[e]}getAllActiveQueryTargets(){return this.Lr.activeTargetIds}isActiveQueryTarget(e){return this.Lr.activeTargetIds.has(e)}start(){return this.Lr=new sh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class oh{Ur(e){}shutdown(){}}class uh{constructor(){this.Kr=()=>this.Gr(),this.Qr=()=>this.jr(),this.Wr=[],this.zr()}Ur(e){this.Wr.push(e)}shutdown(){window.removeEventListener("online",this.Kr),window.removeEventListener("offline",this.Qr)}zr(){window.addEventListener("online",this.Kr),window.addEventListener("offline",this.Qr)}Gr(){yr("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Wr)e(0)}jr(){yr("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Wr)e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const ch={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class hh{constructor(e){this.Hr=e.Hr,this.Jr=e.Jr}Yr(e){this.Xr=e}Zr(e){this.eo=e}onMessage(e){this.no=e}close(){this.Jr()}send(e){this.Hr(e)}so(){this.Xr()}io(e){this.eo(e)}ro(e){this.no(e)}}class lh extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.oo=t+"://"+e.host,this.uo="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}get co(){return!1}ao(t,e,n,r,s){const i=this.ho(t,e);yr("RestConnection","Sending: ",i,n);var a={};return this.lo(a,r,s),this.fo(t,i,a,n).then(e=>(yr("RestConnection","Received: ",e),e),e=>{throw wr("RestConnection",`${t} failed with error: `,e,"url: ",i,"request:",n),e})}_o(e,t,n,r,s,i){return this.ao(e,t,n,r,s)}lo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+gr,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}ho(e,t){var n=ch[e];return`${this.oo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}fo(o,t,n,r){return new Promise((s,i)=>{const a=new lr;a.setWithCredentials(!0),a.listenOnce(ir.COMPLETE,()=>{try{switch(a.getLastErrorCode()){case sr.NO_ERROR:var e=a.getResponseJson();yr("Connection","XHR received:",JSON.stringify(e)),s(e);break;case sr.TIMEOUT:yr("Connection",'RPC "'+o+'" timed out'),i(new _r(Tr.DEADLINE_EXCEEDED,"Request time out"));break;case sr.HTTP_ERROR:var t=a.getStatus();if(yr("Connection",'RPC "'+o+'" failed with status:',t,"response text:",a.getResponseText()),0{h?yr("Connection","Not sending because WebChannel is closed:",e):(c||(yr("Connection","Opening WebChannel transport."),u.open(),c=!0),yr("Connection","WebChannel sending:",e),u.send(e))},Jr:()=>u.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(u,hr.EventType.OPEN,()=>{h||yr("Connection","WebChannel transport opened.")}),d(u,hr.EventType.CLOSE,()=>{h||(h=!0,yr("Connection","WebChannel transport closed"),l.io())}),d(u,hr.EventType.ERROR,e=>{h||(h=!0,wr("Connection","WebChannel transport errored:",e),l.io(new _r(Tr.UNAVAILABLE,"The operation could not be completed")))}),d(u,hr.EventType.MESSAGE,n=>{if(!h){var e=n.data[0];Er(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){yr("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=nr[e];if(void 0!==t)return Da(t)}(n),t=r.message;void 0===e&&(e=Tr.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),h=!0,l.io(new _r(e,t)),u.close()}else yr("Connection","WebChannel received:",e),l.ro(e)}}),d(i,ar.STAT_EVENT,e=>{e.stat===or?yr("Connection","Detected buffering proxy"):e.stat===ur&&yr("Connection","Detected no buffering proxy")}),setTimeout(()=>{l.so()},0),l}}function dh(){return"undefined"!=typeof window?window:null}function fh(){return"undefined"!=typeof document?document:null}function gh(e){return new Ya(e,!0)}class mh{constructor(e,t,n=1e3,r=1.5,s=6e4){this.Hs=e,this.timerId=t,this.mo=n,this.yo=r,this.po=s,this.Io=0,this.To=null,this.Eo=Date.now(),this.reset()}reset(){this.Io=0}Ao(){this.Io=this.po}Ro(e){this.cancel();var t=Math.floor(this.Io+this.bo()),n=Math.max(0,Date.now()-this.Eo),r=Math.max(0,t-n);0(this.Eo=Date.now(),e())),this.Io*=this.yo,this.Iothis.po&&(this.Io=this.po)}Po(){null!==this.To&&(this.To.skipDelay(),this.To=null)}cancel(){null!==this.To&&(this.To.cancel(),this.To=null)}bo(){return(Math.random()-.5)*this.Io}}class ph{constructor(e,t,n,r,s,i,a,o){this.Hs=e,this.vo=n,this.Vo=r,this.connection=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.So=0,this.Do=null,this.Co=null,this.stream=null,this.xo=new mh(e,t)}No(){return 1===this.state||5===this.state||this.ko()}ko(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Oo()}async stop(){this.No()&&await this.close(0)}Mo(){this.state=0,this.xo.reset()}Fo(){this.ko()&&null===this.Do&&(this.Do=this.Hs.enqueueAfterDelay(this.vo,6e4,()=>this.$o()))}Bo(e){this.Lo(),this.stream.send(e)}async $o(){if(this.ko())return this.close(0)}Lo(){this.Do&&(this.Do.cancel(),this.Do=null)}qo(){this.Co&&(this.Co.cancel(),this.Co=null)}async close(e,t){this.Lo(),this.qo(),this.xo.cancel(),this.So++,4!==e?this.xo.reset():t&&t.code===Tr.RESOURCE_EXHAUSTED?(vr(t.toString()),vr("Using maximum backoff delay to prevent overloading the backend."),this.xo.Ao()):t&&t.code===Tr.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Uo(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Zr(t)}Uo(){}auth(){this.state=1;const e=this.Ko(this.So),n=this.So;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.So===n&&this.Go(e,t)},t=>{e(()=>{var e=new _r(Tr.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Qo(e)})})}Go(e,t){const n=this.Ko(this.So);this.stream=this.jo(e,t),this.stream.Yr(()=>{n(()=>(this.state=2,this.Co=this.Hs.enqueueAfterDelay(this.Vo,1e4,()=>(this.ko()&&(this.state=3),Promise.resolve())),this.listener.Yr()))}),this.stream.Zr(e=>{n(()=>this.Qo(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Oo(){this.state=5,this.xo.Ro(async()=>{this.state=0,this.start()})}Qo(e){return yr("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Ko(t){return e=>{this.Hs.enqueueAndForget(()=>this.So===t?e():(yr("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class yh extends ph{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.yt=s}jo(e,t){return this.connection.wo("Listen",e,t)}onMessage(e){this.xo.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(f=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===f?1:"REMOVE"===f?2:"CURRENT"===f?3:"RESET"===f?4:br(),s=t.targetChange.targetIds||[],i=(f=t.targetChange.resumeToken,e.wt?(Er(void 0===f||"string"==typeof f),_s.fromBase64String(f||"")):(Er(void 0===f||f instanceof Uint8Array),_s.fromUint8Array(f||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(f=a).code?Tr.UNKNOWN:Da(f.code),new _r(o,f.message||""));n=new Ga(r,s,i,o||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var i=ro(e,u.document.name),o=Za(u.document.updateTime),c=u.document.createTime?Za(u.document.createTime):qr.min(),h=new Ti({mapValue:{fields:u.document.fields}}),c=_i.newFoundDocument(i,o,c,h),h=u.targetIds||[],u=u.removedTargetIds||[];n=new Ba(h,u,c.key,c)}else if("documentDelete"in t){t.documentDelete;h=t.documentDelete;h.document;u=ro(e,h.document),c=h.readTime?Za(h.readTime):qr.min(),c=_i.newNoDocument(u,c),h=h.removedTargetIds||[];n=new Ba([],h,c.key,c)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=ro(e,l.document),l=l.removedTargetIds||[];n=new Ba([],l,d,null)}else{if(!("filter"in t))return br();{t.filter;const e=t.filter;e.targetId;l=e.count||0,d=new Sa(l),l=e.targetId;n=new Ua(l,d)}}var o,f;return n}(this.yt,e),n=function(e){if(!("targetChange"in e))return qr.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?Za(t.readTime):qr.min()}(e);return this.listener.Wo(t,n)}zo(e){const t={};t.database=ao(this.yt),t.addTarget=function(e,t){let n;var r=t.target;return n=Ci(r)?{documents:fo(e,r)}:{query:go(e,r)},n.targetId=t.targetId,0function(e,t){let n=e.updateTime?Za(e.updateTime):Za(t);return n.isEqual(qr.min())&&(n=Za(t)),new ha(n,e.transformResults||[])}(e,s))):[]),n=Za(e.commitTime);return this.listener.Zo(n,t)}var r,s;return Er(!e.writeResults||0===e.writeResults.length),this.Jo=!0,this.listener.tu()}eu(){const e={};e.database=ao(this.yt),this.Bo(e)}Xo(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>ho(this.yt,e))};this.Bo(t)}}class wh extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.yt=r,this.nu=!1}su(){if(this.nu)throw new _r(Tr.FAILED_PRECONDITION,"The client has already been terminated.")}ao(n,r,s){return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.ao(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Tr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new _r(Tr.UNKNOWN,e.toString())})}_o(n,r,s,i){return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection._o(n,r,s,e,t,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Tr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new _r(Tr.UNKNOWN,e.toString())})}terminate(){this.nu=!0}}class Ih{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.iu=0,this.ru=null,this.ou=!0}uu(){0===this.iu&&(this.cu("Unknown"),this.ru=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.ru=null,this.au("Backend didn't respond within 10 seconds."),this.cu("Offline"),Promise.resolve())))}hu(e){"Online"===this.state?this.cu("Unknown"):(this.iu++,1<=this.iu&&(this.lu(),this.au(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.cu("Offline")))}set(e){this.lu(),this.iu=0,"Online"===e&&(this.ou=!1),this.cu(e)}cu(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}au(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.ou?(vr(t),this.ou=!1):yr("OnlineStateTracker",t)}lu(){null!==this.ru&&(this.ru.cancel(),this.ru=null)}}class bh{constructor(e,t,n,r,s){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.fu=[],this.du=new Map,this._u=new Set,this.wu=[],this.mu=s,this.mu.Ur(e=>{n.enqueueAndForget(async()=>{Nh(this)&&(yr("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t._u.add(4),await Th(t),t.gu.set("Unknown"),t._u.delete(4),await Eh(t)}(this))})}),this.gu=new Ih(n,r)}}async function Eh(e){if(Nh(e))for(const t of e.wu)await t(!0)}async function Th(e){for(const t of e.wu)await t(!1)}function _h(e,t){const n=e;n.du.has(t.targetId)||(n.du.set(t.targetId,t),Ch(n)?Ah(n):qh(n).ko()&&xh(n,t))}function Sh(e,t){const n=e,r=qh(n);n.du.delete(t),r.ko()&&Dh(n,t),0===n.du.size&&(r.ko()?r.Fo():Nh(n)&&n.gu.set("Unknown"))}function xh(e,t){e.yu.Ot(t.targetId),qh(e).zo(t)}function Dh(e,t){e.yu.Ot(t),qh(e).Ho(t)}function Ah(t){t.yu=new ja({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),ne:e=>t.du.get(e)||null}),qh(t).start(),t.gu.uu()}function Ch(e){return Nh(e)&&!qh(e).No()&&0Gc(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{yr("RemoteStore","Retrying IndexedDB access"),await n(),e._u.delete(1),await Eh(e)})}function Lh(t,n){return n().catch(e=>Rh(t,e,n))}async function Mh(e){const t=e,n=Bh(t);let r=0(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.fu.length&&n.Fo();break}r=e.batchId,function(e,t){e.fu.push(t);const n=Bh(e);n.ko()&&n.Yo&&n.Xo(t.mutations)}(t,e)}catch(e){await Rh(t,e)}var s;Fh(t)&&Oh(t)}function Fh(e){return Nh(e)&&!Bh(e).No()&&0{xh(n,e)})}).bind(null,t),Zr:(async function(e,t){kh(e),Ch(e)?(e.gu.hu(t),Ah(e)):e.gu.set("Unknown")}).bind(null,t),Wo:(async function(e,r,t){if(e.gu.set("Online"),r instanceof Ga&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.du.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.du.delete(n),e.yu.removeTarget(n))}(e)}catch(t){yr("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await Rh(e,t)}else if(r instanceof Ba?e.yu.Kt(r):r instanceof Ua?e.yu.Jt(r):e.yu.jt(r),!t.isEqual(qr.min()))try{const r=await Gc(e.localStore);0<=t.compareTo(r)&&await function(r,s){const e=r.yu.Zt(s);return e.targetChanges.forEach((e,t)=>{if(0{const t=r.du.get(e);var n;t&&(r.du.set(e,t.withResumeToken(_s.EMPTY_BYTE_STRING,t.snapshotVersion)),Dh(r,e),n=new Jo(t.target,e,1,t.sequenceNumber),xh(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){yr("RemoteStore","Failed to raise snapshot:",r),await Rh(e,r)}}).bind(null,t)}),t.wu.push(async e=>{e?(t.pu.Mo(),Ch(t)?Ah(t):t.gu.set("Unknown")):(await t.pu.stop(),kh(t))})),t.pu}function Bh(t){return t.Iu||(t.Iu=function(e,t,n){const r=e;return r.su(),new vh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.yt,n)}(t.datastore,t.asyncQueue,{Yr:(async function(e){Bh(e).eu()}).bind(null,t),Zr:(async function(e,t){t&&Bh(e).Yo&&await async function(e,t){if(xa(n=t.code)&&n!==Tr.ABORTED){const n=e.fu.shift();Bh(e).Mo(),await Lh(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await Mh(e)}var n}(e,t),Fh(e)&&Oh(e)}).bind(null,t),tu:(async function(e){const t=Bh(e);for(const n of e.fu)t.Xo(n.mutations)}).bind(null,t),Zo:(async function(e,t,n){const r=e.fu.shift(),s=Yo.from(r,t,n);await Lh(e,()=>e.remoteSyncer.applySuccessfulWrite(s)),await Mh(e)}).bind(null,t)}),t.wu.push(async e=>{e?(t.Iu.Mo(),await Mh(t)):(await t.Iu.stop(),0{})}static createAndSchedule(e,t,n,r,s){const i=Date.now()+n,a=new Uh(e,t,i,r,s);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new _r(Tr.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Gh(e,t){if(vr("AsyncQueue",`${t}: ${e}`),us(e))return new _r(Tr.UNAVAILABLE,`${t}: ${e}`);throw e}class Kh{constructor(n){this.comparator=n?(e,t)=>n(e,t)||jr.comparator(e.key,t.key):(e,t)=>jr.comparator(e.key,t.key),this.keyedMap=ka(),this.sortedSet=new pi(this.comparator)}static emptySet(e){return new Kh(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof Kh))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new Kh;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class jh{constructor(){this.Tu=new pi(jr.comparator)}track(e){var t=e.doc.key,n=this.Tu.get(t);!n||0!==e.type&&3===n.type?this.Tu=this.Tu.insert(t,e):3===e.type&&1!==n.type?this.Tu=this.Tu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Tu=this.Tu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Tu=this.Tu.remove(t):1===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):br()}Eu(){const n=[];return this.Tu.inorderTraversal((e,t)=>{n.push(t)}),n}}class $h{constructor(e,t,n,r,s,i,a,o,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,r,s){const i=[];return t.forEach(e=>{i.push({type:0,doc:e})}),new $h(e,t,Kh.emptySet(t),i,n,r,!0,!1,s)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&ji(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r$i(e),ji),this.onlineState="Unknown",this.Ru=new Set}}async function Wh(e,t){const n=e,r=t.query;let s=!1,i=n.queries.get(r);if(i||(s=!0,i=new Qh),s)try{i.Au=await n.onListen(r)}catch(e){const n=Gh(e,`Initialization of query '${Qi(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,i),i.listeners.push(t),t.bu(n.onlineState),!i.Au||t.Pu(i.Au)&&Yh(n)}async function Hh(e,t){const n=e,r=t.query;let s=!1;const i=n.queries.get(r);if(i){const e=i.listeners.indexOf(t);0<=e&&(i.listeners.splice(e,1),s=0===i.listeners.length)}if(s)return n.queries.delete(r),n.onUnlisten(r)}function Yh(e){e.Ru.forEach(e=>{e.next()})}class Xh{constructor(e,t,n){this.query=e,this.vu=t,this.Vu=!1,this.Su=null,this.onlineState="Unknown",this.options=n||{}}Pu(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new $h(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Vu?this.Du(e)&&(this.vu.next(e),t=!0):this.Cu(e,this.onlineState)&&(this.xu(e),t=!0),this.Su=e,t}onError(e){this.vu.error(e)}bu(e){this.onlineState=e;let t=!1;return this.Su&&!this.Vu&&this.Cu(this.Su,e)&&(this.xu(this.Su),t=!0),t}Cu(e,t){return!e.fromCache||(!this.options.Nu||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Du(e){if(0jc(t,o,a).next(e=>(o.apply(t),e)).next(e=>s.Cs.removeMatchingKeysForTargetId(t,u.targetId).next(()=>s.Cs.addMatchingKeys(t,i,u.targetId)).next(()=>s.localDocuments.getLocalViewOfDocuments(t,e.Wi,e.zi)).next(()=>e.Wi)))}(this.localStore,new Zh(this.yt),this.documents,this.Mu.id),t=this.$u(this.documents);for(const e of this.queries)await async function(e,n,r=Oa()){const s=await $c(e,Ui(ou(n.bundledQuery))),i=e;return i.persistence.runTransaction("Save named query","readwrite",e=>{var t=Za(n.readTime);if(0<=s.snapshotVersion.compareTo(t))return i.Ns.saveNamedQuery(e,n);t=s.withResumeToken(_s.EMPTY_BYTE_STRING,t);return i.qi=i.qi.insert(t.targetId,t),i.Cs.updateTargetData(e,t).next(()=>i.Cs.removeMatchingKeysForTargetId(e,s.targetId)).next(()=>i.Cs.addMatchingKeys(e,r,s.targetId)).next(()=>i.Ns.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Bu:this.collectionGroups,Lu:e}}}function tl(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class nl{constructor(e){this.key=e}}class rl{constructor(e){this.key=e}}class sl{constructor(e,t){this.query=e,this.qu=t,this.Uu=null,this.hasCachedResults=!1,this.current=!1,this.Ku=Oa(),this.mutatedKeys=Oa(),this.Gu=Hi(e),this.Qu=new Kh(this.Gu)}get ju(){return this.qu}Wu(e,t){const o=t?t.zu:new jh,u=(t||this).Qu;let c=(t||this).mutatedKeys,h=u,l=!1;const d="F"===this.query.limitType&&u.size===this.query.limit?u.last():null,f="L"===this.query.limitType&&u.size===this.query.limit?u.first():null;if(e.inorderTraversal((e,t)=>{const n=u.get(e),r=zi(this.query,t)?t:null,s=!!n&&this.mutatedKeys.has(n.key),i=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?s!==i&&(o.track({type:3,doc:r}),a=!0):this.Hu(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0this.query.limit;){const e="F"===this.query.limitType?h.last():h.first();h=h.delete(e.key),c=c.delete(e.key),o.track({type:1,doc:e})}return{Qu:h,zu:o,$i:l,mutatedKeys:c}}Hu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Qu;this.Qu=e.Qu,this.mutatedKeys=e.mutatedKeys;const s=e.zu.Eu();s.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return br()}};return n(e)-n(t)}(e.type,t.type)||this.Gu(e.doc,t.doc)),this.Ju(n);var i=t?this.Yu():[],a=0===this.Ku.size&&this.current?1:0,o=a!==this.Uu;return this.Uu=a,0!==s.length||o?{snapshot:new $h(this.query,e.Qu,r,s,e.mutatedKeys,0==a,o,!1,!!n&&0this.qu=this.qu.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.qu=this.qu.delete(e)),this.current=e.current)}Yu(){if(!this.current)return[];const t=this.Ku;this.Ku=Oa(),this.Qu.forEach(e=>{this.Zu(e.key)&&(this.Ku=this.Ku.add(e.key))});const n=[];return t.forEach(e=>{this.Ku.has(e)||n.push(new rl(e))}),this.Ku.forEach(e=>{t.has(e)||n.push(new nl(e))}),n}tc(e){this.qu=e.Hi,this.Ku=Oa();var t=this.Wu(e.documents);return this.applyChanges(t,!0)}ec(){return $h.fromInitialDocuments(this.query,this.Qu,this.mutatedKeys,0===this.Uu,this.hasCachedResults)}}class il{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class al{constructor(e){this.key=e,this.nc=!1}}class ol{constructor(e,t,n,r,s,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.sc={},this.ic=new Aa(e=>$i(e),ji),this.rc=new Map,this.oc=new Set,this.uc=new pi(jr.comparator),this.cc=new Map,this.ac=new bc,this.hc={},this.lc=new Map,this.fc=Xu.vn(),this.onlineState="Unknown",this.dc=void 0}get isPrimaryClient(){return!0===this.dc}}async function ul(n,e,t,r,s){n._c=(e,i,t)=>async function(e,t,n){let r=t.view.Wu(i);r.$i&&(r=await zc(e.localStore,t.query,!1).then(({documents:e})=>t.view.Wu(e,r)));var s=n&&n.targetChanges.get(t.targetId),s=t.view.applyChanges(r,e.isPrimaryClient,s);return yl(e,t.targetId,s.Xu),s.snapshot}(n,e,t);const i=await zc(n.localStore,e,!0),a=new sl(e,i.Hi),o=a.Wu(i.documents),u=qa.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState,s),c=a.applyChanges(o,n.isPrimaryClient,u);yl(n,t,c.Xu);var h=new il(e,t,a);return n.ic.set(e,h),n.rc.has(t)?n.rc.get(t).push(e):n.rc.set(t,[e]),c.snapshot}async function cl(e,t,n){const r=_l(e);try{const e=await function(e,s){const i=e,a=Pr.now(),o=s.reduce((e,t)=>e.add(t.key),Oa());let u,c;return i.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=Ca,r=Oa();return i.Gi.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>i.localDocuments.getOverlayedDocuments(n,t)).next(e=>{u=e;const t=[];for(const n of s){const s=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),s=ea(r.transform,e||null);null!=s&&(null===n&&(n=Ti.empty()),n.set(r.field,s))}return n||null}(n,u.get(n.key).overlayedDocument);null!=s&&t.push(new wa(n.key,s,function r(e){const s=[];return ws(e.fields,(e,t)=>{const n=new Kr([e]);if(js(t)){const e=r(t.mapValue).fields;if(0===e.length)s.push(n);else for(const t of e)s.push(n.child(t))}else s.push(n)}),new Ei(s)}(s.value.mapValue),la.exists(!0)))}return i.mutationQueue.addMutationBatch(n,a,t,s)}).next(e=>{var t=(c=e).applyToLocalDocumentSet(u,r);return i.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:c.batchId,changes:Ra(u)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.hc[e.currentUser.toKey()];r=r||new pi(Fr),r=r.insert(t,n),e.hc[e.currentUser.toKey()]=r}(r,e.batchId,n),await wl(r,e.changes),await Mh(r.remoteStore)}catch(e){const t=Gh(e,"Failed to persist write");n.reject(t)}}async function hl(e,t){const r=e;try{const e=await Kc(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.cc.get(t);n&&(Er(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0{var n=t.view.bu(s);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.bu(n)&&(r=!0)}),r&&Yh(t)}(t.eventManager,s),r.length&&t.sc.Wo(r),t.onlineState=s,t.isPrimaryClient&&t.sharedClientState.setOnlineState(s)}}async function dl(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const s=e;return s.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=s.Gi.newChangeBuffer({trackRemovals:!0});return function(e,t,r,s){const i=r.batch,n=i.keys();let a=rs.resolve();return n.forEach(n=>{a=a.next(()=>s.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);Er(null!==t),e.version.compareTo(t)<0&&(i.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),s.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,i))}(s,e,r,n).next(()=>n.apply(e)).next(()=>s.mutationQueue.performConsistencyCheck(e)).next(()=>s.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>s.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=Oa();for(let n=0;ns.localDocuments.getDocuments(e,t))})}(n.localStore,t);gl(n,r,null),fl(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await wl(n,e)}catch(e){await ns(e)}}function fl(e,t){(e.lc.get(t)||[]).forEach(e=>{e.resolve()}),e.lc.delete(t)}function gl(e,t,n){const r=e;let s=r.hc[r.currentUser.toKey()];if(s){const e=s.get(t);e&&(n?e.reject(n):e.resolve(),s=s.remove(t)),r.hc[r.currentUser.toKey()]=s}}function ml(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.rc.get(e))t.ic.delete(r),n&&t.sc.wc(r,n);t.rc.delete(e),t.isPrimaryClient&&t.ac.ls(e).forEach(e=>{t.ac.containsKey(e)||pl(t,e)})}function pl(e,t){e.oc.delete(t.path.canonicalString());var n=e.uc.get(t);null!==n&&(Sh(e.remoteStore,n),e.uc=e.uc.remove(t),e.cc.delete(n),vl(e))}function yl(e,t,n){for(const r of n)r instanceof nl?(e.ac.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.uc.get(n)||e.oc.has(r)||(yr("SyncEngine","New document in limbo: "+n),e.oc.add(r),vl(e))}(e,r)):r instanceof rl?(yr("SyncEngine","Document no longer in limbo: "+r.key),e.ac.removeReference(r.key,t),e.ac.containsKey(r.key)||pl(e,r.key)):br()}function vl(e){for(;0{o.push(s._c(n,t,r).then(e=>{var t;(e||r)&&s.isPrimaryClient&&s.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(i.push(e),t=Vc.Ci(n.targetId,e),a.push(t))}))}),await Promise.all(o),s.sc.Wo(i),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>rs.forEach(t,t=>rs.forEach(t.Si,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>rs.forEach(t.Di,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!us(e))throw e;yr("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.qi.get(t),n=e.snapshotVersion,s=e.withLastLimboFreeSnapshotVersion(n);r.qi=r.qi.insert(t,s)}}}(s.localStore,a))}async function Il(r,e){const s=r;if(Tl(s),_l(s),!0===e&&!0!==s.dc){const r=s.sharedClientState.getAllActiveQueryTargets(),e=await bl(s,r.toArray());s.dc=!0,await Ph(s.remoteStore,!0);for(const r of e)_h(s.remoteStore,r)}else if(!1===e&&!1!==s.dc){const r=[];let n=Promise.resolve();s.rc.forEach((e,t)=>{s.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(ml(s,t),Qc(s.localStore,t,!0))),Sh(s.remoteStore,t)}),await n,await bl(s,r),function(){const n=s;n.cc.forEach((e,t)=>{Sh(n.remoteStore,t)}),n.ac.fs(),n.cc=new Map,n.uc=new pi(jr.comparator)}(),s.dc=!1,await Ph(s.remoteStore,!1)}}async function bl(t,n){const r=t,s=[],i=[];for(const t of n){let e;const h=r.rc.get(t);if(h&&0!==h.length){e=await $c(r.localStore,Ui(h[0]));for(const t of h){const n=r.ic.get(t),h=(a=r,o=n,c=u=void 0,c=await zc((u=a).localStore,o.query,!0),c=o.view.tc(c),u.isPrimaryClient&&yl(u,o.targetId,c.Xu),await c);h.snapshot&&i.push(h.snapshot)}}else{const h=await Wc(r.localStore,t);e=await $c(r.localStore,h),await ul(r,El(h),t,!1,e.resumeToken)}s.push(e)}var a,o,u,c;return r.sc.Wo(i),s}function El(e){return Mi(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Tl(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=hl.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.cc.get(t);if(r&&r.nc)return Oa().add(r.key);{let e=Oa();const r=n.rc.get(t);if(!r)return e;for(const t of r){const r=n.ic.get(t);e=e.unionWith(r.view.ju)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const s=r.cc.get(t),i=s&&s.key;if(i){let e=new pi(jr.comparator);e=e.insert(i,_i.newNoDocument(i,qr.min()));const n=Oa().add(i),s=new Pa(qr.min(),new Map,new wi(Fr),e,n);await hl(r,s),r.uc=r.uc.remove(i),r.cc.delete(t),vl(r)}else await Qc(r.localStore,t,!1).then(()=>ml(r,t,n)).catch(ns)}).bind(null,t),t.sc.Wo=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,s=n.queries.get(t);if(s){for(const t of s.listeners)t.Pu(e)&&(r=!0);s.Au=e}}r&&Yh(n)}).bind(null,t.eventManager),t.sc.wc=(function(e,t,n){const r=e,s=r.queries.get(t);if(s)for(const e of s.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function _l(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=dl.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const s=e;return s.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return s.mutationQueue.lookupMutationBatch(t,r).next(e=>(Er(null!==e),n=e.keys(),s.mutationQueue.removeMutationBatch(t,e))).next(()=>s.mutationQueue.performConsistencyCheck(t)).next(()=>s.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>s.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>s.localDocuments.getDocuments(t,n))})}(r.localStore,t);gl(r,t,n),fl(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await wl(r,e)}catch(n){await ns(n)}}).bind(null,t),t}class Sl{constructor(){this.synchronizeTabs=!1}async initialize(e){this.yt=gh(e.databaseInfo.databaseId),this.sharedClientState=this.gc(e),this.persistence=this.yc(e),await this.persistence.start(),this.localStore=this.Ic(e),this.gcScheduler=this.Tc(e,this.localStore),this.indexBackfillerScheduler=this.Ec(e,this.localStore)}Tc(e,t){return null}Ec(e,t){return null}Ic(e){return Bc(this.persistence,new Pc,e.initialUser,this.yt)}yc(e){return new Dc(Cc.Bs,this.yt)}gc(e){return new ah}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class xl extends Sl{constructor(e,t,n){super(),this.Ac=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ac.initialize(this,e),await _l(this.Ac.syncEngine),await Mh(this.Ac.remoteStore),await this.persistence.li(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}Ic(e){return Bc(this.persistence,new Pc,e.initialUser,this.yt)}Tc(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new sc(n,e.asyncQueue,t)}Ec(e,t){var n=new gs(t,this.persistence);return new fs(e.asyncQueue,n)}yc(e){var t=Oc(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Ku.withCacheSize(this.cacheSizeBytes):Ku.DEFAULT;return new Lc(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,dh(),fh(),this.yt,this.sharedClientState,!!this.forceOwnership)}gc(e){return new ah}}class Dl extends xl{constructor(e,t){super(e,t,!1),this.Ac=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Ac.syncEngine;this.sharedClientState instanceof ih&&(this.sharedClientState.syncEngine={Fr:(async function(e,t,n,r){var s=e,i=await function(e,n){const r=e,s=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>s.Tn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):rs.resolve(null)))}(s.localStore,t);null!==i?("pending"===n?await Mh(s.remoteStore):"acknowledged"===n||"rejected"===n?(gl(s,t,r||null),fl(s,t),s.localStore.mutationQueue.An(t)):br(),await wl(s,i)):yr("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),$r:(async function(e,t,n,r){const s=e;if(s.dc)yr("SyncEngine","Ignoring unexpected query state notification.");else{var i=s.rc.get(t);if(i&&0{Sh(r.remoteStore,e),ml(r,e)}).catch(ns)}}).bind(null,t),vi:(function(e){return e.localStore.persistence.vi()}).bind(null,t),Mr:(async function(e,t){const n=e;return Hc(n.localStore,t).then(e=>wl(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.li(async e=>{await Il(this.Ac.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}gc(e){var t=dh();if(!ih.C(t))throw new _r(Tr.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=Oc(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new ih(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class Al{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>ll(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){yr("SyncEngine","User change. New user:",t.toKey());const r=await Uc(n.localStore,t);n.currentUser=t,(e=n).lc.forEach(e=>{e.forEach(e=>{e.reject(new _r(Tr.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.lc.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await wl(n,r.ji)}}).bind(null,this.syncEngine),await Ph(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new zh}createDatastore(e){var t,n,r,s,i=gh(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new lh(t));return n=e.authCredentials,r=e.appCheckCredentials,s=t,e=i,new wh(n,r,s,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,s=e=>ll(this.syncEngine,e,0),i=new(uh.C()?uh:oh),new bh(t,n,r,s,i);var t,n,r,s,i}createSyncEngine(e,t){return function(e,t,n,r,s,i,a){const o=new ol(e,t,n,r,s,i);return a&&(o.dc=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;yr("RemoteStore","RemoteStore shutting down."),t._u.add(5),await Th(t),t.mu.shutdown(),t.gu.set("Unknown")}(this.remoteStore)}}function Cl(e,t,n){if(!n)throw new _r(Tr.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Nl(e,t,n,r){if(!0===t&&!0===r)throw new _r(Tr.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function kl(e){if(!jr.isDocumentKey(e))throw new _r(Tr.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Rl(e){if(jr.isDocumentKey(e))throw new _r(Tr.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Ll(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20{this.muted||e(t)},0)}}class Hl{constructor(e,t){this.Pc=e,this.yt=t,this.metadata=new Sr,this.buffer=new Uint8Array,this.vc=new TextDecoder("utf-8"),this.Vc().then(e=>{e&&e.Ou()?this.metadata.resolve(e.ku.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.ku)}`))},e=>this.metadata.reject(e))}close(){return this.Pc.cancel()}async getMetadata(){return this.metadata.promise}async mc(){return await this.getMetadata(),this.Vc()}async Vc(){var e=await this.Sc();if(null===e)return null;var t=this.vc.decode(e),n=Number(t);isNaN(n)&&this.Dc(`length string (${t}) is not valid number`);t=await this.Cc(n);return new Jh(JSON.parse(t),e.length+n)}xc(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Sc(){for(;this.xc()<0&&!await this.Nc(););if(0===this.buffer.length)return null;var e=this.xc();e<0&&this.Dc("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Cc(e){for(;this.buffer.lengthno(r.yt,e))},i=await r._o("BatchGetDocuments",n,s,t.length),a=new Map;i.forEach(e=>{const t=(n=r.yt,"found"in(e=e)?function(e,t){Er(!!t.found),t.found.name,t.found.updateTime;var n=ro(e,t.found.name),r=Za(t.found.updateTime),s=t.found.createTime?Za(t.found.createTime):qr.min(),i=new Ti({mapValue:{fields:t.found.fields}});return _i.newFoundDocument(n,r,s,i)}(n,e):"missing"in e?function(e,t){Er(!!t.missing),Er(!!t.readTime);var n=ro(e,t.missing),r=Za(t.readTime);return _i.newNoDocument(n,r)}(n,e):br());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());Er(!!t),o.push(t)}),o}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new Ta(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=jr.fromPath(t);this.mutations.push(new _a(n,this.precondition(n)))}),await async function(e,t){const n=e,r=ao(n.yt)+"/documents",s={writes:t.map(e=>ho(n.yt,e))};await n.ao("Commit",r,s)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw br();t=qr.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new _r(Tr.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(qr.min())?la.exists(!1):la.updateTime(t):la.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return la.exists(!0);if(t.isEqual(qr.min()))throw new _r(Tr.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return la.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class Xl{constructor(e,t,n,r,s){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=s,this.kc=n.maxAttempts,this.xo=new mh(this.asyncQueue,"transaction_retry")}run(){--this.kc,this.Oc()}Oc(){this.xo.Ro(async()=>{const t=new Yl(this.datastore),e=this.Mc(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Fc(e)}))}).catch(e=>{this.Fc(e)})})}Mc(e){try{var t=this.updateFunction(e);return!bs(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Fc(e){0(this.Oc(),Promise.resolve()))):this.deferred.reject(e)}$c(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!xa(t)}}class Jl{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=fr.UNAUTHENTICATED,this.clientId=Mr.R(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{yr("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(yr("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new _r(Tr.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new Sr;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=Gh(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function Zl(e,t){e.asyncQueue.verifyOperationInProgress(),yr("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await Uc(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function ed(e,n){e.asyncQueue.verifyOperationInProgress();var t=await td(e);yr("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>Vh(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>Vh(n.remoteStore,t)),e.onlineComponents=n}async function td(e){return e.offlineComponents||(yr("FirestoreClient","Using default OfflineComponentProvider"),await Zl(e,new Sl)),e.offlineComponents}async function nd(e){return e.onlineComponents||(yr("FirestoreClient","Using default OnlineComponentProvider"),await ed(e,new Al)),e.onlineComponents}function rd(e){return td(e).then(e=>e.persistence)}function sd(e){return td(e).then(e=>e.localStore)}function id(e){return nd(e).then(e=>e.remoteStore)}function ad(e){return nd(e).then(e=>e.syncEngine)}async function od(e){const t=await nd(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=Tl(e);let r,s;const i=n.ic.get(t);if(i)r=i.targetId,n.sharedClientState.addLocalQueryTarget(r),s=i.view.ec();else{const e=await $c(n.localStore,Ui(t));n.isPrimaryClient&&_h(n.remoteStore,e);const i=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,s=await ul(n,t,r,"current"===i,e.resumeToken)}return s}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ic.get(t),s=n.rc.get(r.targetId);if(1!ji(e,t))),void n.ic.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await Qc(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),Sh(n.remoteStore,r.targetId),ml(n,r.targetId)}).catch(ns)):(ml(n,r.targetId),await Qc(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function ud(e,t,n={}){const r=new Sr;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,s,i,a){const e=new Wl({next:e=>{r.enqueueAndForget(()=>Hh(n,o));var t=e.docs.has(s);!t&&e.fromCache?a.reject(new _r(Tr.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&i&&"server"===i.source?a.reject(new _r(Tr.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):a.resolve(e)},error:e=>a.reject(e)}),o=new Xh(Fi(s.path),e,{includeMetadataChanges:!0,Nu:!0});return Wh(n,o)}(await od(e),e.asyncQueue,t,n,r)),r.promise}function cd(e,t,n={}){const r=new Sr;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,s){const i=new Wl({next:e=>{n.enqueueAndForget(()=>Hh(t,a)),e.fromCache&&"server"===r.source?s.reject(new _r(Tr.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):s.resolve(e)},error:e=>s.reject(e)}),a=new Xh(e,i,{includeMetadataChanges:!0,Nu:!0});return Wh(t,a)}(await od(e),e.asyncQueue,t,n,r)),r.promise}function hd(e,t,n,r){const s=(n=n,t=gh(t),i="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return zl(e,void 0);if(e instanceof ArrayBuffer)return zl(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(i),t=t,new Hl(n,t));var i;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var s=await n.getMetadata();if(await function(e,t){const n=e,r=Za(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Ns.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,s))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:s.totalDocuments,bytesLoaded:s.totalBytes,totalDocuments:s.totalDocuments,totalBytes:s.totalBytes}),Promise.resolve(new Set);r._updateProgress(tl(s));const a=new el(s,t.localStore,n.yt);let e=await n.mc();for(;e;){const t=await a.Fu(e);t&&r._updateProgress(t),e=await n.mc()}var i=await a.complete();return await wl(t,i.Lu,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Ns.saveBundleMetadata(e,t))}(t.localStore,s),r._completeWith(i.progress),Promise.resolve(i.Bu)}catch(t){return wr("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await ad(e),s,r)})}class ld{constructor(){this.Bc=Promise.resolve(),this.Lc=[],this.qc=!1,this.Uc=[],this.Kc=null,this.Gc=!1,this.Qc=!1,this.jc=[],this.xo=new mh(this,"async_queue_retry"),this.Wc=()=>{var e=fh();e&&yr("AsyncQueue","Visibility state changed to "+e.visibilityState),this.xo.Po()};const e=fh();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Wc)}get isShuttingDown(){return this.qc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.zc(),this.Hc(e)}enterRestrictedMode(e){if(!this.qc){this.qc=!0,this.Qc=e||!1;const t=fh();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Wc)}}enqueue(e){if(this.zc(),this.qc)return new Promise(()=>{});const t=new Sr;return this.Hc(()=>this.qc&&this.Qc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Lc.push(e),this.Jc()))}async Jc(){if(0!==this.Lc.length){try{await this.Lc[0](),this.Lc.shift(),this.xo.reset()}catch(e){if(!us(e))throw e;yr("AsyncQueue","Operation failed with retryable error: "+e)}0this.Jc())}}Hc(e){var t=this.Bc.then(()=>(this.Gc=!0,e().catch(e=>{throw this.Kc=e,this.Gc=!1,vr("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.Gc=!1,e))));return this.Bc=t}enqueueAfterDelay(e,t,n){this.zc(),-1this.Yc(e));return this.Uc.push(r),r}zc(){this.Kc&&br()}verifyOperationInProgress(){}async Xc(){for(var e;await(e=this.Bc),e!==this.Bc;);}Zc(e){for(const t of this.Uc)if(t.timerId===e)return!0;return!1}ta(t){return this.Xc().then(()=>{this.Uc.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.Uc)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Xc()})}ea(e){this.jc.push(e)}Yc(e){var t=this.Uc.indexOf(e);this.Uc.splice(t,1)}}function dd(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class fd{constructor(){this._progressObserver={},this._taskCompletionResolver=new Sr,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var gd,md,pd;class yd extends Pl{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new ld,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||wd(this),this._firestoreClient.terminate()}}function vd(e){return e._firestoreClient||wd(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function wd(e){var t,n,r,s,i,a=e._freezeSettings(),a=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",s=e._persistenceKey,i=a,new ps(n,r,s,i.host,i.ssl,i.experimentalForceLongPolling,i.experimentalAutoDetectLongPolling,i.useFetchStreams));e._firestoreClient=new Jl(e._authCredentials,e._appCheckCredentials,e._queue,a)}function Id(e,n,r){const s=new Sr;return e.asyncQueue.enqueue(async()=>{try{await Zl(e,r),await ed(e,n),s.resolve()}catch(e){const n=e;if(!("FirebaseError"===(t=n).name?t.code===Tr.FAILED_PRECONDITION||t.code===Tr.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code||11===t.code)))throw n;wr("Error enabling offline persistence. Falling back to persistence disabled: "+n),s.reject(n)}var t}).then(()=>s.promise)}function bd(e){return function(e){const t=new Sr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;Nh(n.remoteStore)||yr("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.lc.get(e)||[];r.push(t),n.lc.set(e,r)}catch(e){const n=Gh(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await ad(e),t)),t.promise}(vd(e=Ml(e,yd)))}function Ed(e){return(n=vd(e=Ml(e,yd))).asyncQueue.enqueue(async()=>{const e=await rd(n),t=await id(n);return e.setNetworkEnabled(!0),function(){const e=t;return e._u.delete(0),Eh(e)}()});var n}function Td(e){return(n=vd(e=Ml(e,yd))).asyncQueue.enqueue(async()=>{const e=await rd(n),t=await id(n);return e.setNetworkEnabled(!1),async function(){const e=t;e._u.add(0),await Th(e),e.gu.set("Offline")}()});var n}function _d(t,e){return n=vd(t=Ml(t,yd)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Ns.getNamedQuery(e,t))}(await sd(n),r)).then(e=>e?new Ul(t,null,e.query):null);var n,r}function Sd(e){if(e._initialized||e._terminated)throw new _r(Tr.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class xd{constructor(e){this._byteString=e}static fromBase64String(e){try{return new xd(_s.fromBase64String(e))}catch(e){throw new _r(Tr.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new xd(_s.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class Dd{constructor(...e){for(let t=0;tt.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}na(){if(this.path)for(let e=0;eu.covers(e.field))}else u=null,c=a.fieldTransforms;return new kd(new Ti(o),u,c)}class Pd extends Ad{_toFieldTransform(e){if(2!==e.sa)throw 1===e.sa?e.ha(`${this._methodName}() can only appear at the top level of your update data`):e.ha(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof Pd}}function qd(e,t,n){return new Md({sa:3,fa:t.settings.fa,methodName:e._methodName,oa:n},t.databaseId,t.yt,t.ignoreUndefinedProperties)}class Bd extends Ad{_toFieldTransform(e){return new ca(e.path,new ta)}isEqual(e){return e instanceof Bd}}class Ud extends Ad{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=qd(this,e,!0),n=this._a.map(e=>zd(e,t)),r=new na(n);return new ca(e.path,r)}isEqual(e){return this===e}}class Gd extends Ad{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=qd(this,e,!0),n=this._a.map(e=>zd(e,t)),r=new sa(n);return new ca(e.path,r)}isEqual(e){return this===e}}class Kd extends Ad{constructor(e,t){super(e),this.wa=t}_toFieldTransform(e){var t=new aa(e.yt,Ji(e.yt,this.wa));return new ca(e.path,t)}isEqual(e){return this===e}}function jd(e,s,i,t){const a=e.da(1,s,i);Yd("Data must be an object, but it was:",a,t);const o=[],u=Ti.empty();ws(t,(e,t)=>{var n=Zd(s,e,i);t=m(t);var r=a.ca(n);if(t instanceof Pd)o.push(n);else{const e=zd(t,r);null!=e&&(o.push(n),u.set(n,e))}});var n=new Ei(o);return new Rd(u,n,a.fieldTransforms)}function $d(e,t,n,r,s,i){const a=e.da(1,t,n),o=[Xd(t,r,n)],u=[s];if(i.length%2!=0)throw new _r(Tr.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f{var n=zd(t,r.ra(e));null!=n&&(s[e]=n)}),{mapValue:{fields:s}}}function Hd(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Pr||e instanceof Cd||e instanceof xd||e instanceof Bl||e instanceof Ad)}function Yd(e,t,n){if(!Hd(n)||("object"!=typeof(s=n)||null===s||Object.getPrototypeOf(s)!==Object.prototype&&null!==Object.getPrototypeOf(s))){var r=Ll(n);throw"an object"===r?t.ha(e+" a custom object"):t.ha(e+" "+r)}var s}function Xd(e,t,n){if((t=m(t))instanceof Dd)return t._internalPath;if("string"==typeof t)return Zd(e,t);throw ef("Field path arguments must be of type string or ",e,!1,void 0,n)}const Jd=new RegExp("[~\\*/\\[\\]]");function Zd(t,n,r){if(0<=n.search(Jd))throw ef(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new Dd(...n.split("."))._internalPath}catch(e){throw ef(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function ef(e,t,n,r,s){var i=r&&!r.isEmpty(),a=void 0!==s;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let u="";return(i||a)&&(u+=" (found",i&&(u+=` in field ${r}`),a&&(u+=` in document ${s}`),u+=")"),new _r(Tr.INVALID_ARGUMENT,o+e+u)}function tf(e,t){return e.some(e=>e.isEqual(t))}class nf{constructor(e,t,n,r,s){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new Bl(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new rf(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(sf("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class rf extends nf{data(){return super.data()}}function sf(e,t){return"string"==typeof t?Zd(e,t):(t instanceof Dd?t:t._delegate)._internalPath}function af(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new _r(Tr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class of{}class uf extends of{}function cf(e,t,...n){let r=[];t instanceof of&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof lf).length,n=e.filter(e=>e instanceof hf).length;if(1e._parse(t)).filter(e=>0a.length)throw new _r(Tr.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let u=0;u, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${s.toString()}'`);var n=Vi(e);null!==n&&If(0,s,n)}const r=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(0<=t.indexOf(e.op))return e.op;return null}(e.filters,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new _r(Tr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new _r(Tr.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}function If(e,t,n){if(!n.isEqual(t))throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class bf{convertValue(e,t="none"){switch(Ls(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Ds(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(As(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw br()}}convertObject(e,n){const r={};return ws(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new Cd(Ds(e.latitude),Ds(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=function e(t){var n=t.mapValue.fields.__previous_value__;return Cs(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ns(e));default:return null}}convertTimestamp(e){var t=xs(e);return new Pr(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=Ur.fromString(e);Er(Io(n));const r=new ys(n.get(1),n.get(3)),s=new jr(n.popFirst(5));return r.isEqual(t)||vr(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),s}}function Ef(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class Tf extends bf{constructor(e){super(),this.firestore=e}convertBytes(e){return new xd(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Bl(this.firestore,null,t)}}class _f{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Sf extends nf{constructor(e,t,n,r,s,i){super(e,t,n,r,i),this._firestore=e,this._firestoreImpl=e,this.metadata=s}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new xf(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(sf("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class xf extends Sf{data(e={}){return super.data(e)}}class Df{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new _f(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new xf(this._firestore,this._userDataWriter,e.key,e,new _f(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new _r(Tr.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(i,t){if(i._snapshot.oldDocs.isEmpty()){let n=0;return i._snapshot.docChanges.map(e=>{var t=new xf(i._firestore,i._userDataWriter,e.doc.key,e.doc,new _f(i._snapshot.mutatedKeys.has(e.doc.key),i._snapshot.fromCache),i.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new xf(i._firestore,i._userDataWriter,e.doc.key,e.doc,new _f(i._snapshot.mutatedKeys.has(e.doc.key),i._snapshot.fromCache),i.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=s.indexOf(e.doc.key),s=s.delete(e.doc.key)),1!==e.type&&(s=s.add(e.doc),r=s.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return br()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function Af(e,t){return e instanceof Sf&&t instanceof Sf?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof Df&&t instanceof Df&&e._firestore===t._firestore&&Ql(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class Cf extends bf{constructor(e){super(),this.firestore=e}convertBytes(e){return new xd(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Bl(this.firestore,null,t)}}function Nf(t){t=Ml(t,Bl);const n=Ml(t.firestore,yd),e=vd(n),r=new Cf(n);return function(e,t){const n=new Sr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(t);s.isFoundDocument()?n.resolve(s):s.isNoDocument()?n.resolve(null):n.reject(new _r(Tr.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){var r=Gh(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await sd(e),t,n)),n.promise}(e,t._key).then(e=>new Sf(n,r,t._key,e,new _f(null!==e&&e.hasLocalMutations,!0),t.converter))}function kf(t){t=Ml(t,Ul);const n=Ml(t.firestore,yd),e=vd(n),r=new Cf(n);return function(e,t){const n=new Sr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await zc(e,t,!0),i=new sl(t,s.Hi),a=i.Wu(s.documents),o=i.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=Gh(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await sd(e),t,n)),n.promise}(e,t._query).then(e=>new Df(n,r,t,e))}function Rf(e,t,n){e=Ml(e,Bl);var r=Ml(e.firestore,yd),s=Ef(e.converter,t,n);return Of(r,[Vd(Od(r),"setDoc",e._key,s,null!==e.converter,n).toMutation(e._key,la.none())])}function Lf(e,t,n,...r){e=Ml(e,Bl);var s=Ml(e.firestore,yd),i=Od(s);let a;return a="string"==typeof(t=m(t))||t instanceof Dd?$d(i,"updateDoc",e._key,t,n,r):jd(i,"updateDoc",e._key,t),Of(s,[a.toMutation(e._key,la.exists(!0))])}function Mf(t,...n){var e;t=m(t);let r={includeMetadataChanges:!1},s=0;"object"!=typeof n[s]||dd(n[s])||(r=n[s],s++);var i={includeMetadataChanges:r.includeMetadataChanges};if(dd(n[s])){const t=n[s];n[s]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[s+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[s+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,u;if(t instanceof Bl)o=Ml(t.firestore,yd),u=Fi(t._key.path),a={next:e=>{n[s]&&n[s](Vf(o,t,e))},error:n[s+1],complete:n[s+2]};else{const c=Ml(t,Ul);o=Ml(c.firestore,yd),u=c._query;const h=new Cf(o);a={next:e=>{n[s]&&n[s](new Df(o,h,c,e))},error:n[s+1],complete:n[s+2]},af(t._query)}return function(e,t,n,r){const s=new Wl(r),i=new Xh(t,s,n);return e.asyncQueue.enqueueAndForget(async()=>Wh(await od(e),i)),()=>{s.bc(),e.asyncQueue.enqueueAndForget(async()=>Hh(await od(e),i))}}(vd(o),u,i,a)}function Ff(e,t){return function(e,t){const n=new Wl(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Ru.add(t),t.next()}(await od(e),n)),()=>{n.bc(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Ru.delete(t)}(await od(e),n))}}(vd(e=Ml(e,yd)),dd(t)?t:{next:t})}function Of(e,t){return function(e,t){const n=new Sr;return e.asyncQueue.enqueueAndForget(async()=>cl(await ad(e),t,n)),n.promise}(vd(e),t)}function Vf(e,t,n){var r=n.docs.get(t._key),s=new Cf(e);return new Sf(e,s,t._key,r,new _f(n.hasPendingWrites,n.fromCache),t.converter)}const Pf={maxAttempts:5};class qf{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=Od(e)}set(e,t,n){this._verifyNotCommitted();const r=Bf(e,this._firestore),s=Ef(r.converter,t,n),i=Vd(this._dataReader,"WriteBatch.set",r._key,s,null!==r.converter,n);return this._mutations.push(i.toMutation(r._key,la.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var s=Bf(e,this._firestore);let i;return i="string"==typeof(t=m(t))||t instanceof Dd?$d(this._dataReader,"WriteBatch.update",s._key,t,n,r):jd(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,la.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=Bf(e,this._firestore);return this._mutations=this._mutations.concat(new Ta(t._key,la.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0{if(!e||1!==e.length)return br();const t=e[0];if(t.isFoundDocument())return new nf(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new nf(this._firestore,r,n._key,null,n.converter);throw br()})}set(e,t,n){var r=Bf(e,this._firestore),s=Ef(r.converter,t,n),s=Vd(this._dataReader,"Transaction.set",r._key,s,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){var s=Bf(e,this._firestore),i="string"==typeof(t=m(t))||t instanceof Dd?$d(this._dataReader,"Transaction.update",s._key,t,n,r):jd(this._dataReader,"Transaction.update",s._key,t);return this._transaction.update(s._key,i),this}delete(e){var t=Bf(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=Bf(e,this._firestore),n=new Cf(this._firestore);return super.get(e).then(e=>new Sf(this._firestore,n,t._key,e._document,new _f(!1,!1),t.converter))}}function Gf(t,n,e){t=Ml(t,yd);var r=Object.assign(Object.assign({},Pf),e);return function(){if(r.maxAttempts<1)throw new _r(Tr.INVALID_ARGUMENT,"Max attempts must be at least 1")}(),function(t,n,r){const s=new Sr;return t.asyncQueue.enqueueAndForget(async()=>{var e=await nd(t).then(e=>e.datastore);new Xl(t.asyncQueue,e,r,n,s).run()}),s.promise}(vd(t),e=>n(new Uf(t,e)),r)}gd=mg.SDK_VERSION,gr=gd,mg._registerComponent(new g("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),s=new yd(new Cr(e.getProvider("auth-internal")),new Lr(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new _r(Tr.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new ys(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:!0},n),s._setSettings(n),s},"PUBLIC").setMultipleInstances(!0)),mg.registerVersion(dr,"3.8.3",void 0),mg.registerVersion(dr,"3.8.3","esm2017");function Kf(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new _r("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function jf(){if("undefined"==typeof Uint8Array)throw new _r("unimplemented","Uint8Arrays are not available in this environment.")}function $f(){if("undefined"==typeof atob)throw new _r("unimplemented","Blobs are unavailable in Firestore in this environment.")}class Qf{constructor(e){this._delegate=e}static fromBase64String(e){return $f(),new Qf(xd.fromBase64String(e))}static fromUint8Array(e){return jf(),new Qf(xd.fromUint8Array(e))}toBase64(){return $f(),this._delegate.toBase64()}toUint8Array(){return jf(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function zf(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class Wf{enableIndexedDbPersistence(e,t){return function(e,t){Sd(e=Ml(e,yd));var n=vd(e),r=e._freezeSettings(),s=new Al;return Id(n,s,new xl(s,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){Sd(e=Ml(e,yd));var t=vd(e),n=e._freezeSettings(),r=new Al;return Id(t,r,new Dl(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new _r(Tr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Sr;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!is.C())return Promise.resolve();var t=e+"main";await is.delete(t)}(Oc(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Hf{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof ys||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||wr("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){ql(this._delegate,e,t,n)}enableNetwork(){return Ed(this._delegate)}disableNetwork(){return Td(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,Nl("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return bd(this._delegate)}onSnapshotsInSync(e){return Ff(this._delegate,e)}get app(){if(!this._appCompat)throw new _r("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new cg(this,Kl(this._delegate,e))}catch(e){throw tg(e,"collection()","Firestore.collection()")}}doc(e){try{return new eg(this,jl(this._delegate,e))}catch(e){throw tg(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new ag(this,function(e,t){if(e=Ml(e,Pl),Cl("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new _r(Tr.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Ul(e,null,(t=t,new Li(Ur.emptyPath(),t)))}(this._delegate,e))}catch(e){throw tg(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Gf(this._delegate,e=>t(new Xf(this,e)))}batch(){return vd(this._delegate),new Jf(new qf(this._delegate,e=>Of(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=vd(t=Ml(t,yd)),r=new fd,hd(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return _d(this._delegate,e).then(e=>e?new ag(this,e):null)}}class Yf extends bf{constructor(e){super(),this.firestore=e}convertBytes(e){return new Qf(new xd(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return eg.forKey(t,this.firestore,null)}}class Xf{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Yf(e)}get(e){const t=hg(e);return this._delegate.get(t).then(e=>new sg(this._firestore,new Sf(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=hg(e);return n?(Kf("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=hg(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=hg(e);return this._delegate.delete(t),this}}class Jf{constructor(e){this._delegate=e}set(e,t,n){var r=hg(e);return n?(Kf("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=hg(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=hg(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Zf{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new xf(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new ig(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=Zf.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let s=r.get(t);return s||(s=new Zf(e,new Yf(e),t),r.set(t,s)),s}}Zf.INSTANCES=new WeakMap;class eg{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Yf(e)}static forPath(e,t,n){if(e.length%2!=0)throw new _r("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new eg(t,new Bl(t._delegate,n,new jr(e)))}static forKey(e,t,n){return new eg(t,new Bl(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new cg(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new cg(this.firestore,Kl(this._delegate,e))}catch(e){throw tg(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=m(e))instanceof Bl&&$l(this._delegate,e)}set(e,t){t=Kf("DocumentReference.set",t);try{return t?Rf(this._delegate,e,t):Rf(this._delegate,e)}catch(e){throw tg(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?Lf(this._delegate,e):Lf(this._delegate,e,t,...n)}catch(e){throw tg(e,"updateDoc()","DocumentReference.update()")}}delete(){return Of(Ml((e=this._delegate).firestore,yd),[new Ta(e._key,la.none())]);var e}onSnapshot(...e){var t=ng(e),n=rg(e,e=>new sg(this.firestore,new Sf(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return Mf(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?Nf:"server"===(null==e?void 0:e.source)?function(t){t=Ml(t,Bl);const n=Ml(t.firestore,yd);return ud(vd(n),t._key,{source:"server"}).then(e=>Vf(n,t,e))}:function(t){t=Ml(t,Bl);const n=Ml(t.firestore,yd);return ud(vd(n),t._key).then(e=>Vf(n,t,e))})(this._delegate),t.then(e=>new sg(this.firestore,new Sf(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new eg(this.firestore,e?this._delegate.withConverter(Zf.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function tg(e,t,n){return e.message=e.message.replace(t,n),e}function ng(e){for(const t of e)if("object"==typeof t&&!zf(t))return t;return{}}function rg(e,t){var n;let r;return r=zf(e[0])?e[0]:zf(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class sg{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new eg(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return Af(this._delegate,e._delegate)}}class ig extends sg{data(e){var t=this._delegate.data(e);return void 0!==t||br(),t}}class ag{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Yf(e)}where(e,t,n){try{return new ag(this.firestore,cf(this._delegate,(r=n,s=t,i=sf("where",e),hf._create(i,s,r))))}catch(e){throw tg(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,s,i}orderBy(e,t){try{return new ag(this.firestore,cf(this._delegate,([n,r="asc"]=[e,t],s=r,i=sf("orderBy",n),df._create(i,s))))}catch(e){throw tg(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,s,i}limit(e){try{return new ag(this.firestore,cf(this._delegate,(Fl("limit",t=e),ff._create("limit",t,"F"))))}catch(e){throw tg(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new ag(this.firestore,cf(this._delegate,(Fl("limitToLast",t=e),ff._create("limitToLast",t,"L"))))}catch(e){throw tg(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new ag(this.firestore,cf(this._delegate,function(...e){return gf._create("startAt",e,!0)}(...e)))}catch(e){throw tg(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new ag(this.firestore,cf(this._delegate,function(...e){return gf._create("startAfter",e,!1)}(...e)))}catch(e){throw tg(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new ag(this.firestore,cf(this._delegate,function(...e){return mf._create("endBefore",e,!1)}(...e)))}catch(e){throw tg(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new ag(this.firestore,cf(this._delegate,function(...e){return mf._create("endAt",e,!0)}(...e)))}catch(e){throw tg(e,"endAt()","Query.endAt()")}}isEqual(e){return Ql(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?kf:"server"===(null==e?void 0:e.source)?function(t){t=Ml(t,Ul);const n=Ml(t.firestore,yd),e=vd(n),r=new Cf(n);return cd(e,t._query,{source:"server"}).then(e=>new Df(n,r,t,e))}:function(t){t=Ml(t,Ul);const n=Ml(t.firestore,yd),e=vd(n),r=new Cf(n);return af(t._query),cd(e,t._query).then(e=>new Df(n,r,t,e))})(this._delegate),t.then(e=>new ug(this.firestore,new Df(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=ng(e),n=rg(e,e=>new ug(this.firestore,new Df(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return Mf(this._delegate,t,n)}withConverter(e){return new ag(this.firestore,e?this._delegate.withConverter(Zf.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class og{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new ig(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class ug{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new ag(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new ig(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new og(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new ig(this._firestore,e))})}isEqual(e){return Af(this._delegate,e._delegate)}}class cg extends ag{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new eg(this.firestore,e):null}doc(e){try{return void 0===e?new eg(this.firestore,jl(this._delegate)):new eg(this.firestore,jl(this._delegate,e))}catch(e){throw tg(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=Ml(e.firestore,yd),r=jl(e),s=Ef(e.converter,t);return Of(n,[Vd(Od(e.firestore),"addDoc",r._key,s,null!==e.converter,{}).toMutation(r._key,la.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new eg(this.firestore,e))}isEqual(e){return $l(this._delegate,e._delegate)}withConverter(e){return new cg(this.firestore,e?this._delegate.withConverter(Zf.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function hg(e){return Ml(e,Bl)}const lg={Firestore:Hf,GeoPoint:Cd,Timestamp:Pr,Blob:Qf,Transaction:Xf,WriteBatch:Jf,DocumentReference:eg,DocumentSnapshot:sg,Query:ag,QueryDocumentSnapshot:ig,QuerySnapshot:ug,CollectionReference:cg,FieldPath:class dg{constructor(...e){this._delegate=new Dd(...e)}static documentId(){return new dg(Kr.keyField().canonicalString())}isEqual(e){return(e=m(e))instanceof Dd&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class fg{constructor(e){this._delegate=e}static serverTimestamp(){const e=new Bd("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new fg(e)}static delete(){const e=new Pd("deleteField");return e._methodName="FieldValue.delete",new fg(e)}static arrayUnion(...e){const t=function(...e){return new Ud("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new fg(t)}static arrayRemove(...e){const t=function(...e){return new Gd("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new fg(t)}static increment(e){const t=new Kd("increment",e);return t._methodName="FieldValue.increment",new fg(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,mr.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};md=t.default,pd=(e,t)=>new Hf(e,t,new Wf),md.INTERNAL.registerComponent(new g("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return pd(t,n)},"PUBLIC").setServiceProps(Object.assign({},lg))),md.registerVersion("@firebase/firestore-compat","0.3.3")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-firestore-compat.js - be sure to load firebase-app.js first.")}}); //# sourceMappingURL=firebase-firestore-compat.js.map